ember.js - bind-attr with Controller property -
consider following code:
handlebars template:
<script type="text/x-handlebars" data-template-name="items"> <div {{bind-attr class="isarchiveactive:active"}}> highlighted if archived item 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>
controller:
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; } });
model:
app.item = ds.model.extend({ title: ds.attr('string'), isarchived: ds.attr('boolean') }); app.item.fixtures = [{ id: 1, title: 'geometry', isarchived: true }];
currently, when code runs, bind-attr
inside {{#each}}
blocks update active class correctly when toggling "activate" , "deactivate" buttons. however, bind-attr
outside works onload , not update dynamically.
is there way bind controller attributes , have update on fly.
fixed code(demo css, templates etc. - emberjs.jsbin.com). have make controller.isarchiveactive
computed property reacts on item.isactive
property changes:
isarchiveactive: function() { var items = this.filterby('isarchived', true).filterby('isactive', true); return items.length > 0; }.property('model.@each.isactive')
full app.js code(i needed write more code test it, have different routes etc.):
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') });
Comments
Post a Comment