使用es6时,流星模板自动运行不是功能 [英] Meteor template autorun is not a function when using es6
问题描述
作品
Template.Hello.onRendered(function() {
this.autorun(() => {
console.log('sup');
});
});
无效。
Template.Hello.onRendered(() => {
this.autorun(() => {
console.log('sup');
});
});
错误是TypeError:_this.autorun不是一个函数。
The error is TypeError: _this.autorun is not a function.
使用箭头符号的任何想法给了我们这个错误?
Any ideas why using arrow notation gives us this error?
推荐答案
箭头函数使用词法绑定 this
这意味着这个
将是创建功能时的任何东西。这意味着在使用对象属性(如模板)的对象上创建函数时,您不幸的是使用它。
Arrow functions use lexical binding of this
which means that this
will be whatever it was when the function was created. This means that you unfortunately can't use it when creating functions on objects that use object properties such as the template.
一个小例子就像:
o = {};
o.fn = () => console.log(this);
o.fn(); // not 'o'
o.fn = function () { console.log(this); }
o.fn(); // 'o'
.autorun
一个模板的方法就是需要这个
的功能绑定。
.autorun
is a method of the template so the functional binding of this
is required.
有时候,词法绑定箭头功能很有用,例如回调到 autorun
。在这种情况下,您希望这个
保持与外部范围相同。否则你必须绑定它:
There are times when the lexical binding of arrow functions are useful such as in the callback to autorun
. In that case, you want this
to remain the same as the outer scope. Otherwise you would have to bind it:
Template.Hello.onRendered(() => {
this.autorun(() => {
console.log(this); // the template
});
this.autorun(function () {
console.log(this); // the template
}.bind(this));
this.autorun(function () {
console.log(this); // the callback function
});
});
这篇关于使用es6时,流星模板自动运行不是功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!