Skip to content

Instantly share code, notes, and snippets.

@givanse
Last active August 24, 2016 23:38
Show Gist options
  • Save givanse/32eec4644f383e948cf81a01048dedd0 to your computer and use it in GitHub Desktop.
Save givanse/32eec4644f383e948cf81a01048dedd0 to your computer and use it in GitHub Desktop.
Observing nested properties
import Ember from 'ember';
function buildWithAlias(item) {
// add the alias when the item is being created,
// this might also be done inside an Ember Data model
let foo = {
nephew: Ember.computed.alias('parent.child.nephew')
};
item = Object.assign(item, foo);
return Ember.Object.create(item);
}
export default Ember.Controller.extend({
list: Ember.computed('model', function() {
let model = this.get('model');
return model.map(function(item) {
return buildWithAlias(item);
});
}),
/*
* @each two levels deep is not supported
* https://ember-twiddle.com/c580593125450d241f248d63193d6431?fileTreeShown=false
*/
nephews: Ember.computed('[email protected]', function() {
return this.get('list').map(function(item) {
return item.parent.child.nephew;
})
}),
/*
* You can use intermediate computeds.
*
* Ember < 2.0.0 (reduceComputed)
* https://github.com/emberjs/ember.js/pull/2711
* http://emberjs.com/blog/2013/08/29/ember-1-0-rc8.html#toc_array-computed
*
* Ember > 2.0.0 (Glimmer)
* https://github.com/emberjs/ember.js/pull/11513#issue
*/
listObservingAlias: Ember.computed.mapBy('list', 'nephew'),
actions: {
plusOneAll: function() {
this.get('list').forEach(function(item) {
let val = item.get('parent.child.nephew');
item.set('parent.child.nephew', val + 1);
});
}
}
});
import Ember from 'ember';
const serverPayload = [
{parent: {child: {nephew: 404}}},
{parent: {child: {nephew: 405}}},
{parent: {child: {nephew: 406}}}
];
export default Ember.Route.extend({
model: function() {
return serverPayload;
}
});
<h1>Observing nested properties</h1>
{{outlet}}
two levels deep @each:
<br>
{{#each nephews as |value|}}
{{value}}
<br>
{{/each}}
<br>
alias + mapBy:
<br>
{{#each listObservingAlias as |value|}}
{{value}}
<br>
{{/each}}
<br>
<button {{action "plusOneAll"}}>+1 all</button>
<br><hr><br>
underlying list:
<br>
{{#each list as |item|}}
{{item.parent.child.nephew}}
{{/each}}
{
"version": "0.10.4",
"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.7.0",
"ember-data": "2.7.0",
"ember-template-compiler": "2.7.0"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment