Autostart Meteor pattern is not a function when using es6

Job

Template.Hello.onRendered(function() {
  this.autorun(() => {
    console.log('sup');
  });
});

Does not work.

Template.Hello.onRendered(() => {
  this.autorun(() => {
    console.log('sup');
  });
});

Error: TypeError: _this.autorun is not a function.

Any ideas why using arrow notation gives us this error?

+4
source share
1 answer

Arrow functions use lexical binding this, which means it thiswill be what it was when the function was created. This means that, unfortunately, you cannot use it when creating functions for objects that use object properties, such as a template.

A small example:

o = {};
o.fn = () => console.log(this);
o.fn(); // not 'o'

o.fn = function () { console.log(this); }
o.fn(); // 'o'

.autorunis a template method, therefore functional binding is required this.

, , , autorun. , this , . :

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

Source: https://habr.com/ru/post/1625893/


All Articles