registerHelper
实现非常简单:
Handlebars.registerHelper = function(name, fn, inverse) {
if(inverse) { fn.not = inverse; }
this.helpers[name] = fn;
};
没有检查是否已经定义了助手,助手只是简单地写入Handlebars.helpers
对象,就是这样。
不过,没有什么能阻止您添加自己的registerHelper
抱怨版本。你可以这样做:
Handlebars.paranoidRegisterHelper = function(name, fn, inverse) {
if(name in this.helpers)
throw 'Someone is trying to redefine the ' + name + ' helper';
this.registerHelper(name, fn, inverse);
};
然后使用paranoidRegisterHelper
相同的助手名称两次会引发异常。
演示:http: //jsfiddle.net/ambiguous/3Knj3/
如果您想继续registerHelper
用作名称,那么在猴子修补它之前只需安全地引用它:
var registerHelper = Handlebars.registerHelper;
Handlebars.registerHelper = function(name, fn, inverse) {
if(name in this.helpers)
throw 'Someone is trying to redefine the ' + name + ' helper';
registerHelper.apply(this, arguments);
};
演示:http: //jsfiddle.net/ambiguous/hUu2r/