ES6 Arrow Function question


#1

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

#2

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.


#3

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!


#4

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.


#5

There are some other instances where you do don’t want to replace a function with a fat arrow too, in the top level of Meteor.publish for example.

Perhaps, we should try an get list of places where this it could be problematic.