Works
Template.Hello.onRendered(function() {
this.autorun(() => {
console.log('sup');
});
});
Doesn't work.
Template.Hello.onRendered(() => {
this.autorun(() => {
console.log('sup');
});
});
The error is TypeError: _this.autorun is not a function.
Any ideas why using arrow notation gives us this error?
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.
A small example is something like:
o = {};
o.fn = () => console.log(this);
o.fn(); // not 'o'
o.fn = function () { console.log(this); }
o.fn(); // 'o'
.autorun
is a method of the template so the functional binding of this
is required.
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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With