javascript - ES6 的 Handlebars 助手

标签 javascript handlebars.js handlebarshelper

我想写一个 block 助手来检查是否应该为某个 Angular 色显示一个部分:

{{#allowApprover "EMP"}} 
<!-- content -->
{{/allowApprover}}

助手的定义如下:

allowApprover: (currentRole, options) => {
     return permit(currentRole) ? options.fn(this) : options.inverse(this)
}

上面的代码不起作用,我猜是因为 this 在箭头中的行为不同,但我不知道如何让它起作用,另一个问题是 是什么options.fn 到底做什么?

最佳答案

我遇到了同样的问题,错误信息是:

Cannot read property '_sections' of null 

正如@torazaburo 评论的那样,在这种情况下,您应该编写一个常规函数而不是箭头函数。

这就是为什么,用 Mozilla 的一篇很棒的文章的话来说。

ES6 in depth arrow functions

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.

继续,在同一篇文章中:

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.

关于javascript - ES6 的 Handlebars 助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32062585/

相关文章:

javascript - 从 handlebars 助手返回 html 对象

javascript - ReactJS 中 map 内的映射

javascript - 不带实例调用原型(prototype)

javascript - document.cookie 只存储第一个键值对?

ember.js - Playframework 2.1 预编译 ember Handlebars

handlebars.js - Handlebars 中的查找助手

javascript - 尝试使用 jQuery 创建显示/隐藏切换内容?

ember.js - Handlebars 的 Ember 源代码托管 URL?

templates - Handlebars If-Else If-Else 与字符串相等函数

backbone.js - Handlebars 获取循环索引