Skip to content

Instantly share code, notes, and snippets.

@WenInCode
Last active December 7, 2016 03:48
Show Gist options
  • Save WenInCode/5596716e1499fb3cb86c77806222800e to your computer and use it in GitHub Desktop.
Save WenInCode/5596716e1499fb3cb86c77806222800e to your computer and use it in GitHub Desktop.
computed variations example
import Ember from 'ember';
const {
computed,
get,
} = Ember;
export default Ember.Component.extend({
things: [],
thingCount: computed('things.[]', function() {
let things = get(this, 'things');
return things.length;
}),
thingCountWithoutBrace: computed('things', function() {
let things = get(this, 'things');
return things.length;
}),
actions: {
addThing() {
let things = get(this, 'things');
things.pushObject({name: 'thing'});
},
},
});
import Ember from 'ember';
const {
computed,
get,
set,
} = Ember;
export default Ember.Component.extend({
thing: [
{ name: 'harold', count: 12 },
{ name: 'tim', count: 1 },
{ name: 'Chaaaaad!!', count: -12 },
],
thingCounts: computed('thing.@each.count', function() {
let thing = get(this, 'thing');
let counts = thing.map((obj) => {
return get(obj, 'count');
});
return counts.toString();
}),
thingCountsWithoutEach: computed('thing.[]', function() {
let thing = get(this, 'thing');
let counts = thing.map((obj) => {
return get(obj, 'count');
});
return counts.toString();
}),
actions: {
incrementCount(index) {
let thing = get(this, 'thing');
let th = thing.objectAt(index);
let thCount = get(th, 'count');
set(th, 'count', thCount += 1);
},
},
});
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Ember Twiddle'
});
{{computed-brace}}
{{computed-each-attr}}
<h1>Computed with []</h1>
<div>
<h2>thing count with things.[]</h2>
{{thingCount}}
</div>
<div>
<h2>thing count with things</h2>
{{thingCountWithoutBrace}}
</div>
<ul>
{{#each things as |thing|}}
<li>{{thing.name}}</li>
{{/each}}
</ul>
<button {{action 'addThing'}}>Add a thing</button>
<hr />
<h1>Computed with @each.attribute</h1>
{{#each thing as |th|}}
<p>{{th.name}}: {{th.count}}</p>
{{/each}}
<button {{action 'incrementCount' 0}}>Increment harold's Count</button>
<button {{action 'incrementCount' 1}}>Increment tim's Count</button>
<button {{action 'incrementCount' 2}}>Increment Chaaaaad!!'s Count</button>
<div>
<h2>Thing Counts with @each.count</h2>
<p>{{thingCounts}}</p>
</div>
<div>
<h2>Thing Counts without @each.count</h2>
<p>{{thingCountsWithoutEach}}</p>
</div>
{
"version": "0.10.6",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.9.0",
"ember-data": "2.9.0",
"ember-template-compiler": "2.9.0",
"ember-testing": "2.9.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment