请考虑以下代码:
把手模板:
<script type="text/x-handlebars" data-template-name="items">
<div {{bind-attr class="isArchiveActive:active"}}>
Will be highlighted if an archived item is active.
</div>
<ul class="archived-items">
{{#each}}
<li {{bind-attr class="isActive:active"}}>
<button {{action "activate" this}}>Activate</button>
<button {{action "deactivate" this}}>Deactivate</button>
</li>
{{/each}}
</ul>
</script>
控制器:
App.ItemsController = Ember.ArrayController.extend({
actions: {
activate: function(item) {
item.set('isActive', true);
},
deactivate: function(item) {
item.set('isActive', false);
}
},
isActive: false,
isArchiveActive: function() {
var items = this.filterBy('isArchived', true).filterBy('isActive', true);
return items.length > 0;
}
});
型号:
App.Item = DS.Model.extend({
title: DS.attr('string'),
isArchived: DS.attr('boolean')
});
App.Item.FIXTURES = [{
id: 1,
title: 'Geometry',
isArchived: true
}];
目前,当此代码运行时,bind-attr
块内的{{#each}}
会在切换&#34;激活&#34;时正确更新活动类。和&#34;停用&#34;纽扣。但是,bind-attr
外部仅适用于onLoad并且不会动态更新。
是否有办法绑定控制器属性并让它在运行中更新。
答案 0 :(得分:1)
修正了您的代码(使用css,模板等进行演示 - emberjs.jsbin.com )。您必须使controller.isArchiveActive
计算属性,以便它对item.isActive
属性更改做出反应:
isArchiveActive: function() {
var items = this.filterBy('isArchived', true).filterBy('isActive', true);
return items.length > 0;
}.property('model.@each.isActive')
完整的app.js代码(我需要编写更多代码以便我可以测试它,你可能有不同的路由等):
App = Ember.Application.create();
App.Store = DS.Store.extend({
adapter: DS.FixtureAdapter
});
App.Router.map(function() {
this.route('items');
});
App.Item = DS.Model.extend({
title: DS.attr('string'),
isArchived: DS.attr('boolean')
});
App.Item.FIXTURES = [{
id: 1,
title: 'Geometry',
isArchived: true
},
{
id: 2,
title: 'AnotherArchived',
isArchived: true
},
{
id: 3,
title: 'SomethingOtherNotArchived',
isArchived: false
}];
App.ItemsRoute = Ember.Route.extend({
model: function() {
return this.store.find('item');
}
});
App.ItemsController = Ember.ArrayController.extend({
actions: {
activate: function(item) {
item.set('isActive', true);
},
deactivate: function(item) {
item.set('isActive', false);
}
},
isActive: false,
isArchiveActive: function() {
var items = this.filterBy('isArchived', true).filterBy('isActive', true);
return items.length > 0;
}.property('model.@each.isActive')
});