Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access template instance from helpers in Meteor 0.8.0 Blaze

The change in behavior for the Template.foo.rendered callback in Meteor 0.8.0 means that we don't get to automatically use the rendered callback as a way to manipulate the DOM whenever the contents of the template change. One way to achieve this is by using reactive helpers as in https://github.com/avital/meteor-ui-new-rendered-callback. The reactive helpers should theoretically help performance by only being triggered when relevant items change.

However, there is now a new problem: the helper no longer has access to the template instance, like the rendered callback used to. This means that anything used to maintain state on the template instance cannot be done by helpers.

Is there a way to access both the template instance's state as well as use reactive helpers to trigger DOM updates in Blaze?

like image 931
Andrew Mao Avatar asked Apr 01 '14 20:04

Andrew Mao


People also ask

What are meteor templates?

Meteor templates are using three top level tags. The first two are head and body. These tags perform the same functions as in regular HTML. The third tag is template. This is the place, where we connect HTML to JavaScript.

What is Blaze in meteor?

Blaze is Meteor's built-in reactive rendering library. Usually, templates are written in Spacebars, a variant of Handlebars designed to take advantage of Tracker, Meteor's reactivity system. These templates are compiled into JavaScript UI components that are rendered by the Blaze library.


2 Answers

In the latest versions you can use more convenient Template.instance() instead.

like image 184
Igor Loskutov Avatar answered Sep 24 '22 17:09

Igor Loskutov


Now there's Template.instance() which allows you to access a template's instance in helpers. e.g

Template.myTemplate.helpers({
    myvalue: function() {
        var tmpl = Template.instance();

        ...
    }
});

Along with reactiveDict, you could use them to pass values down set in the rendered callback.

Template.myTemplate.created = function() {
    this.templatedata = new ReactiveDict();

}
Template.myTemplate.rendered = function() {
    this.templatedata.set("myname", "value");
};

Template.myTemplate.helpers({
    myvalue: function() {
        var tmpl = Template.instance();
        return tmpl.templatedata.get('myname');
    }
});
like image 31
Tarang Avatar answered Sep 22 '22 17:09

Tarang