Template.instance()和这个有什么区别?使用其中一个是否有优势?
Template.name.onRendered( function() {
var template = Template.instance();
var instance = this;
});
Run Code Online (Sandbox Code Playgroud)
当在生命周期事件内部onCreated
,onRendered
或者onDestroyed
,Template.instance()
将返回与this
这些回调注册函数中相同的对象时,this
将由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>
Run Code Online (Sandbox Code Playgroud)
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");
});
Run Code Online (Sandbox Code Playgroud)
但是在模板助手中,this
绑定到模板的数据上下文,而不是模板实例本身,因此Template.instance()
必须使用它来访问执行帮助程序的模板实例.
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();
}
});
Run Code Online (Sandbox Code Playgroud)
最后,在模板事件中,this
也绑定到模板的数据上下文,但是template
使用可以用作速记的附加参数调用事件处理程序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);
}
});
Run Code Online (Sandbox Code Playgroud)