gpt4 book ai didi

meteor - Template.instance() 和这个的区别

转载 作者:行者123 更新时间:2023-12-04 01:32:33 25 4
gpt4 key购买 nike

Template.instance() 和这个有什么区别?使用其中一个有优势吗?

Template.name.onRendered( function() {
var template = Template.instance();
var instance = this;
});

最佳答案

当在诸如onCreatedonRenderedonDestroyed 等生命周期事件中时,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>

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

但是在模板助手中,this 绑定(bind)到模板的数据上下文,而不是模板实例本身,因此需要使用 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();
}
});

最后,在模板事件中,this 也绑定(bind)到模板的数据上下文,但是事件处理程序是用一个额外的 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);
}
});

关于meteor - Template.instance() 和这个的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534580/

25 4 0