视图中的attributeBindings不会根据模型更改进行更新

时间:2013-05-29 05:24:09

标签: ember.js

我想知道我是否只是在做一些根本错误的事情,但我正在尝试让模型在视图中定义样式属性。因此,例如,ember视图使用卡片模板,并以模型属性颜色支持的<div style="color: green">...</div>开头。当我通过App.Card.find(2).set("color", "color: red").save()在其他地方更改它时,我希望模板更新值,但它什么都不做。直接在模板中使用{{ bindAttr style model.color }}确保值保持同步,但是我有一个额外的ember-view div元素。

http://jsfiddle.net/dbhWg/3/

的javascript:

App = Ember.Application.create();

App.Store = DS.Store.extend({
    adapter: 'DS.FixtureAdapter'
});

App.Router.map(function () {
    // put your routes here
});

App.IndexRoute = Ember.Route.extend({
    model: function () {
        return App.Card.find()
    }
});

App.Card = DS.Model.extend({
    color: DS.attr('string'),
});

App.Card.FIXTURES = [{
    id: 1,
    color: "color: green"
}, {
    id: 2,
    color: "color: blue"
}];

App.CardView = Ember.View.extend({
    templateName: "card",
    attributeBindings: ['style'],
    style: function () {
        return this.get('controller.model.color')
    }.property('controller.model'),
    didInsertElement: function () {
        App.Card.find(2).set('color', "color: red").save()
        console.log(App.Card.find(2).get('color'))
    }
});

模板:

<script type="text/x-handlebars" data-template-name="card">
    <h1> HELLO THERE </h1>
</script>

<script type="text/x-handlebars">
    <h2> Welcome to Ember.js </h2>
    {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
    {{#each item in model}} 
      {{render "card" item}} 
    {{/each}}
</script>

1 个答案:

答案 0 :(得分:1)

您忘记为计算属性中的颜色添加dependecency

style: function () {
    return this.get('controller.model.color')
}.property('controller.model.color'),

Working Fiddle

<击> 据我所知,您无法使用bindAttr更新CSS 我建议您使用类,而是按如下方式定义类:

.red{
  color: red;
}

.green{
  color: green;
}

.blue: {
  color: blue;
}

更新灯具为:

App.Card.FIXTURES = [{
  id: 1,
  color: "green"  
}, {
  id: 2,
  color: "blue"
}];

将颜色绑定到class,如下所示

App.CardView = Ember.View.extend({
    templateName: "card",
    classNameBindings: ['color'],
    color: function () {
        return this.get('controller.model.color');
    }.property('controller.model.color'),
    didInsertElement: function () {
        App.Card.find(2).set('color', "red").save();
        console.log(App.Card.find(2).get('color'));
    }
});