Hey all. I’m updating an older Meteor app to the latest version and just spent about an hour trying to figure out why this._id was undefined only to figure out that when updating the function call to ES6 format, that is what broke it. Can anyone please explain why this snippet works whereas the one below it doesn’t? Any insight would be very much appreciated!
Working:
Template.body.events({
'click .toggle-checked': function() {
// Set the checked property to the opposite of its current value
Meteor.call('setChecked', this._id, ! this.checked);
}
});
Not working:
Template.body.events({
'click .toggle-checked': () => {
// Set the checked property to the opposite of its current value
Meteor.call('setChecked', this._id, ! this.checked);
}
});
With the first code, this is bound by Meteor to the correct value.
With an arrow function, this is never bound in the function (it uses current/outer value), so Meteor event handler autobind doesn’t work.
Ahh. I get it now. I originally thought we were replacing all function()'s with fat arrows, but now I see the practical application behind it. Very much appreciated, thank you!
Yes, it’s pretty dangerous to replace every function with fat arrow.
IMHO, you should only use fat arrow when you want to create a small anonymous function, functionnal style, or when you know what you are doing and want to use the outer this.