Emberjs计算了模型中的属性

时间:2013-12-29 06:15:54

标签: javascript ember.js model

我正在尝试在模型中使用计算属性来呈现模板中的数据。这是我模型的片段:

App.ApplicationRoute = Ember.Route.extend({
    model: function() {  
    ...
        divStyle: function() {
           return "height:" + this.get('height') + "px; color:"+ this.get('color') +";";
        }.property('height', 'color')
    }
}

这是我模板的片段:

{{#each}} <div {{bindAttr style="divStyle"}}</div> {{/each}}

但我收到以下错误:“断言失败:属性必须是数字,字符串或布尔值,而不是函数”。我正在关注这篇文章:Ember.js binding a css style in a template并且不知何故它不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:5)

您需要在模型类上定义它,而不是在模型挂钩内部,或者与路径关联的控制器类(application)。

答案 1 :(得分:4)

您没有在model函数中定义计算属性。您必须在控制器或路径上定义计算属性。 See here for more information about computed properties


但是当您尝试在each循环中计算样式时,您需要采用不同的方法来获取每个项目的样式。

我会像这样使用Ember Handlebars Helper来设置样式。

辅助

Ember.Handlebars.registerBoundHelper("getStyle", function(o){
    return "height: " + o.height + "px;" +
           "width: " + o.width + "px;" +
           "background-color: " + o.color; 
});

用法

{{#each}}
    <div style="{{unbound getStyle this}}"></div>
{{/each}}

演示

您可以看到有效JSBin here。 该演示使用每个循环和包含样式信息的模型来创建:

Screenshot

我希望这会有所帮助。

相关问题