Skip to content

Instantly share code, notes, and snippets.

@denzo
Last active January 11, 2016 04:05
Show Gist options
  • Save denzo/fe54e72463d0cd17d9a0 to your computer and use it in GitHub Desktop.
Save denzo/fe54e72463d0cd17d9a0 to your computer and use it in GitHub Desktop.
Computed Properties with @each
import Ember from 'ember';
export default Ember.Controller.extend({
appName:'Ember Twiddle',
owner: Ember.computed(function() {
return this.store.createRecord('owner');
}),
allItems: Ember.computed(function() {
return [
Ember.Object.create({id: 0, status: 'clean'}),
Ember.Object.create({id: 1, status: 'clean'}),
Ember.Object.create({id: 2, status: 'clean'}),
Ember.Object.create({id: 3, status: 'clean'}),
Ember.Object.create({id: 4, status: 'dirty'}),
];
}),
cleanItems: Ember.computed('[email protected]',function() {
return this.get('allItems').filterBy('status', 'clean');
}),
dirtyItems: Ember.computed('[email protected]',function() {
return this.get('allItems').filterBy('status', 'dirty');
}),
actions: {
addCleanItem() {
this.store.createRecord('item', {
owner: this.get('owner'),
status: 'clean'
})
},
addDirtyItem() {
this.store.createRecord('item', {
owner: this.get('owner'),
status: 'dirty'
})
},
updateItem(item, status) {
console.log(item);
item.set('status', status);
}
}
});
<button {{action "addCleanItem"}}>Add clean item</button>
<button {{action "addDirtyItem"}}>Add dirty item</button>
<hr>
<h3>All items ({{owner.items.length}})</h3>
{{#each owner.items as |item|}}
<li>{{item.id}} ({{item.status}})</li>
{{/each}}
<h3>Clean items ({{owner.cleanItems.length}})</h3>
{{#each owner.cleanItems as |item|}}
<li>{{item.id}} <button {{action "updateItem" item "dirty"}}>Make dirty</button></li>
{{/each}}
<h3>Dirty items ({{owner.dirtyItems.length}})</h3>
{{#each owner.dirtyItems as |item|}}
<li>{{item.id}} <button {{action "updateItem" item "clean"}}>Make clean</button></li>
{{/each}}
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('owner'),
status: DS.attr('string')
});
import DS from 'ember-data';
export default DS.Model.extend({
items: DS.hasMany('item'),
cleanItems: Ember.computed('[email protected]',function() {
return this.get('items').filterBy('status', 'clean');
}),
dirtyItems: Ember.computed('[email protected]',function() {
return this.get('items').filterBy('status', 'dirty');
}),
});
{
"version": "0.4.17",
"EmberENV": {
"FEATURES": {}
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.2.0",
"ember-data": "2.2.0",
"ember-template-compiler": "2.2.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment