Handlebars: Don’t use ES6 arrow functions to define helpers
If you use the IMHO great Handlebars templating library in a real world project you need to write custom Handlebars Helpers. This are functions which return a string and which encapsulate your logic to prevent you and your team to implement business logic in templates.
The method Handlebars.registerHelper
has a signature which looks like your bread and butter use case for ES6 arrow functions:
Handlebars.registerHelper( 'important', (...args) => args.join(this.exclamationMark) )`
But an arrow function doesn’t bind this it just inherits it from its defining scope.
const global = this;
Handlebars.registerHelper('isThisGlobalInArrowFunction', () => this === global);
Handlebars.registerHelper('isThisGlobalInOldschoolFunction', function() {
return this === global;
});
The first helper returns always true
The second helper will only return true
if the executing context of it is also global
This is important because Handlebars helpers use this
as the context of the template execution.
So basically just don’t use arrow function to define Handlebars helpers and if you have difficulties to understand Javascripts this
have look at Dmitri Pavlutin Gentle explanation of ‘this’ keyword in JavaScript.