将控制器模型属性传递给把手助手

时间:2013-12-19 21:38:18

标签: ember.js ember-data handlebars.js

我试图在#each循环中使用一个相当简单的Handlebars助手,遍历控制器模型中的项目(它是EmberData使用fixtureAdapter提供的模型集合)。这是模板的基本布局:

{{#each}}
    ....
    {{#each clusters}}
        <span>{{prettifyTimestampTime cluster_timestamp}}</span>
    {{/each}}
{{/each}}

这是我的助手(在coffeescript中):

Ember.Handlebars.registerBoundHelper 'prettifyTimestampTime', (timestamp, options) ->
    d = new Date timestamp
    hours = String(d.getHours() % 12)
    hours = "0#{hours}" if hours.length is 1
    "#{hours}:#{d.getMinutes()}:#{d.getMinutes()}" 

我最初使用Handelbars.registerHelper在Handlebars上设置了这个帮助器,但是我继续传入字符串"cluster_timestamp"(无论我在模板中prettifyTimestampTime之后放置什么,它都会得到解析为String)。

然后,我接着试着通过在引号中包装属性并在options.data.keywords上进行查找来尝试给stukennedy's answer尝试,但是键不在该字典中。

当我尝试使用Ember.Handlebars.registerBoundHelper而不是Bradley Preist's suggestion here时,timestamp参数只是未定义。我注意到,当我尝试访问options.contexts[0]上的任何属性时,他们指向的值为undefined,但密钥就在那里。

此时我感到完全迷失了。欢迎任何方向。这真的是Ember中的一个已知错误,正如stukennedy在之前的SO问题中指出的那样?刚刚开始使用Ember和Handlebars,我宁愿在我的结尾处遇到一些愚蠢的错误,考虑difficult it was for me to also to set up fixtures with Ember data in the first place。 :-P

编辑:看到this question后,我意识到为什么registerHelper不起作用(因为它不会尝试将传入的内容与上下文中当前对象的属性相关联)。然而,由于财产的查找不起作用,我仍然像迷路一样。也许这是承诺的Ember Data问题?唯一令我困惑的是,我正在使用灯具(没有请求),我能够通常使用像cluster_timestamp这样的正常表达来获取属性{{cluster_timestamp}}

1 个答案:

答案 0 :(得分:1)

不要使用registerHelper,http://emberjs.com/guides/templates/writing-helpers/

Ember.Handlebars.helper 'prettifyTimestampTime', (timestamp, options) ->
    d = new Date timestamp
    hours = String(d.getHours() % 12)
    hours = "0#{hours}" if hours.length is 1
    "#{hours}:#{d.getMinutes()}:#{d.getMinutes()}"