如何让把手在上下文中调用get()方法?

时间:2017-07-19 22:20:57

标签: ember.js handlebars.js

我自己使用把手和Ember对象作为上下文。我喜欢它,因为它在Ember + HTMLBars中工作,它似乎调用get()而不是假设context是POJO。

var C = Ember.Object.extend({
  value: Ember.computed(function() { return "hello"; })
});
var template = Handlebars.compile("My ember object: {{value}}");
var str = template(C.create());

assert.equal(str, "My ember object: hello"); // Fails. str == "My ember object: [object Object]"

有没有办法让把手调用get()?

1 个答案:

答案 0 :(得分:0)

您可以使用Handlebars Compiler API添加在名称查找期间自动调用的帮助程序。

function MyCompiler() {
  Handlebars.JavaScriptCompiler.apply(this, arguments);
}
MyCompiler.prototype = new Handlebars.JavaScriptCompiler();

MyCompiler.prototype.nameLookup = function(parent, name, type) {
  if (type === 'context') {
    return this.source.functionCall('helpers.get', '', [parent, JSON.stringify(name)])
  } else {
    return Handlebars.JavaScriptCompiler.prototype.nameLookup.call(this, parent, name, type);
  }
}

var env = Handlebars.create();
env.registerHelper('get', function(parent, name) {
  return parent.get(name);
})

env.JavaScriptCompiler = MyCompiler;

现在问题中的原始示例有效。

var C = Ember.Object.extend({
  value: Ember.computed(function() { return "hello"; })
});
var template = env.compile("My ember object: {{value}}");
var str = template(C.create());

assert.equal(str, "My ember object: hello"); // PASS!

此答案基于this jsfiddle