1

Sorry, ES6 newb here:

Template.hello.onCreated( () => {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
});

Template.hello.helpers({
  counter() {
    return Template.instance().counter.get();
  },
});

Template.hello.events({
  'click button'(event, instance) {
    // increment the counter when button is clicked
    instance.counter.set(instance.counter.get() + 1);
  },
});

When I click on the button I get Cannot read property 'get' of undefined

But when I do

Template.hello.onCreated( function(){
  // counter starts at 0
  this.counter = new ReactiveVar(0);
});

it works fine.

So there's something going on with ES6's fat arrow binding of the this keyword that I'm not getting?

fuzzybabybunny
  • 5,146
  • 6
  • 32
  • 58

1 Answers1

4

When Meteor calls the onCreated handler, it binds the function's this value to the template instance. Arrow functions lexically bind this, which means that this inside an arrow function is the same as where the function is defined, in your case probably window. As a result, you are creating a global variable counter instead of assigning it to the template instance.

For onCreated, onRendered, etc., it makes no sense to use arrow functions.

klaussner
  • 2,364
  • 3
  • 25
  • 33
  • 1
    Interesting. I thought that arrow functions were the way *all* functions would need to be written in ES6 going forward? Does this mean in ES6 you actually need to think about which type of function to use especially if you're using `this`? BTW `counter` was indeed created as a global variable. – fuzzybabybunny Jul 31 '16 at 09:16
  • Exactly, both types of functions have their own use cases. Sometimes it doesn't matter which one you choose but callbacks for which the `this` context is provided by a framework (like `onCreated`) are one example where "normal" functions are necessary. Here is a nice article that lists some other cases: https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/. In my projects, I always use `function`s unless arrow functions make the code easier to read. – klaussner Jul 31 '16 at 09:31
  • 1
    Ohhhhhh.... thank you. Super valuable info here. – fuzzybabybunny Jul 31 '16 at 09:35