Skip to content

Instantly share code, notes, and snippets.

@mike-north
Created February 28, 2018 18:16
Show Gist options
  • Save mike-north/817a4b149eb6073aa3f2b3911cecceac to your computer and use it in GitHub Desktop.
Save mike-north/817a4b149eb6073aa3f2b3911cecceac to your computer and use it in GitHub Desktop.
Observing an array
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
init() {
this._super(...arguments);
this.set('myArray', []);
this.set('x', 3);
this.set('arraySum1InvocationCount', 0);
this.set('arraySum2InvocationCount', 0);
},
arraySum1: Ember.computed('myArray', function() {
this.incrementProperty('arraySum1InvocationCount');
return this.get('myArray').reduce((item, acc) => acc + item, 0);
}),
arraySum2: Ember.computed('myArray.[]', function() {
this.incrementProperty('arraySum2InvocationCount');
return this.get('myArray').reduce((item, acc) => acc + item, 0);
}),
actions: {
replaceArray() {
this.set('myArray', []);
},
addToArray(item) {
this.get('myArray').pushObject(item);
}
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
<p><code>arraySum1</code> {{arraySum1}}</p>
<p><code>arraySum2</code> {{arraySum2}}</p>
<p>
<code>arraySum1</code> computed property has been re-calculated {{arraySum1InvocationCount}} time(s)
</p>
<p>
<code>arraySum2</code> computed property has been re-calculated {{arraySum2InvocationCount}} time(s)
</p>
<p>
<button onClick={{action "replaceArray"}}>Click to set myArray to a new array</button>
</p>
<p>
<button onClick={{action "addToArray" x}}>Click to add an item to myArray without replacing it</button>
{{input value=x}}
</p>
<br>
<br>
{
"version": "0.13.0",
"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.16.2",
"ember-template-compiler": "2.16.2",
"ember-testing": "2.16.2"
},
"addons": {
"ember-data": "2.16.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment