Reputation: 15927
I want to write a block helper to check if a section should displayed for a certain role:
{{#allowApprover "EMP"}}
<!-- content -->
{{/allowApprover}}
And the helper is defined like:
allowApprover: (currentRole, options) => {
return permit(currentRole) ? options.fn(this) : options.inverse(this)
}
the above code doesn't work, I guess it's because the this
behaves differently in arrows, but I don't know how to make this work, and another question, what does options.fn
do exactly?
Upvotes: 4
Views: 1704
Reputation: 1986
Estevan is right. But I won't acccept it. My project requires modular functions to be easily testable. So I came up with a workaround. It requires wrapping the method and dropping the use of this
. But it works.
Example:
const helpers = {
ifTruthy: (...args: any[]): HandlebarOptions => {
const { fn, inverse } = args.pop();
const values = args;
const anyIsTruthy = values.some((element) => Boolean(element));
return anyIsTruthy ? fn() : inverse();
}
};
helpersKeys.forEach(key => {
handlebarsInstance.registerHelper(key, function callback(...args) {
const options = args.pop();
const newOptions = { ...options };
newOptions.fn = () => options.fn(this);
newOptions.inverse = () => options.inverse(this);
return helperMethods[key](...args, newOptions);
});
});
Upvotes: 1
Reputation: 1828
I had the same problem, with this error message:
Cannot read property '_sections' of null
As @torazaburo commented, you should, in this case, write a regular function instead of an arrow function.
Here's why, by the words of a great article from Mozilla.
What’s this?
There is one subtle difference in behavior between ordinary function functions and arrow functions. Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
Going forward, in the same article:
Use non-arrow functions for methods that will be called using the object.method() syntax. Those are the functions that will receive a meaningful this value from their caller.
Upvotes: 1