Andrew Mao
Andrew Mao

Reputation: 36900

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?

Upvotes: 9

Views: 10898

Answers (3)

Igor Loskutov
Igor Loskutov

Reputation: 2325

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

Upvotes: 23

Tarang
Tarang

Reputation: 75945

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');
    }
});

Upvotes: 12

Andrew Mao
Andrew Mao

Reputation: 36900

This is currently being tracked as "one of the first things to be added" in post 0.8.0 Meteor:

https://github.com/meteor/meteor/issues/1529

Another related issue is the ability to access data reactively in the rendered callback, which avoids this issue in the first place:

https://github.com/meteor/meteor/issues/2010

Upvotes: 0

Related Questions