问题
What is the difference between Template.instance() and this? Is there an advantage to use one or the other?
Template.name.onRendered( function() {
var template = Template.instance();
var instance = this;
});
回答1:
When inside a lifecycle event such as onCreated
, onRendered
or onDestroyed
, Template.instance()
will return the same object as this
because in these callback registration functions, this
is explicitly set to the current template instance by Meteor.
HTML
<template name="component">
<div class="component">
<p>Hello <em>{{name}}</em>, click the button!</p>
<button type="button">Click me!</button>
<p>You clicked <strong>{{count}}</strong> time(s) on the button.</p>
</div>
</template>
<body>
{{> component name="World"}}
</body>
JS
Template.component.onCreated(function(){
console.log(this == Template.instance());
// use this to access the template instance
this.count = new ReactiveVar(0);
// use this.data to access the data context
console.log(this.data.name == "World");
});
However in template helpers, this
is bound to the data context of the template, not the template instance itself, so using Template.instance()
is necessary to access the template instance executing the helper.
Template.component.helpers({
count: function(){
// use this to access the data context
console.log(this.name);
// use Template.instance() to access the template instance
return Template.instance().count.get();
}
});
Finally, in template events, this
is also bound to the data context of the template, but the event handler is called with an additional template
parameter that you may use as a shorthand to Template.instance()
.
Template.component.events({
"click button": function(event, template){
// use this to access the data context
console.log(this.name);
// use the argument to access the template instance
var currentCount = template.count.get();
template.count.set(currentCount + 1);
}
});
来源:https://stackoverflow.com/questions/32534580/difference-between-template-instance-and-this