meteor helper functions, lambdas and lexical this

2019-07-09 12:01发布

g'day, I read meteor was going all ecmascript 6 - and thought awesome... "I never have to write 'function' again" - so quickly changed a bunch of functions over to lambdas... only to discover it doesn't work :(

If you write a helper function in meteor - you get the data context passed in in the "this" property - but of course, lambdas use a lexical this - so I understand the problem pretty simply.

the thing is - what is not obvious to me is the solution - any idea how you would make a helper function using the () => notation that needs the current data context? It doesn't seem to live anywhere other than "this"?

2条回答
神经病院院长
2楼-- · 2019-07-09 12:31

ECMAScript 2015 didn't deprecate function(). Arrow functions are not shorthand syntax, they have different semantics, most notably, lexical this binding.

You can't have a contextual this in an arrow function - use standard functions instead.

查看更多
闹够了就滚
3楼-- · 2019-07-09 12:36

Use shorthand for defining functions as object properties:

Template.someTemplate.helpers({
  someHelper() {
    console.log(this);
  }
});

But if you really want to use () => syntax, you may be interested in using Template.currentData() instead of this:

Template.someTemplate.helpers({
  someHelper: () => {
    console.log(Template.currentData());
  }
});

From documentation:

Template.currentData()

Inside a helper, returns the data context of the DOM node where the helper was used.

查看更多
登录 后发表回答