Skip to content

Instantly share code, notes, and snippets.

@givanse
Last active August 31, 2016 23:11
Show Gist options
  • Save givanse/39f03f837dd185af9106bdaadafce39b to your computer and use it in GitHub Desktop.
Save givanse/39f03f837dd185af9106bdaadafce39b to your computer and use it in GitHub Desktop.
Cannot define computed properties on literal objects
import Ember from 'ember';
export default Ember.Controller.extend({
hash: {a: 1, b: 2},
hashComputed: Ember.computed('hash', function() {
console.log('hashComputed triggered');
return JSON.stringify(this.get('hash'));
}),
hashPropertyComputed: Ember.computed('hash.a', function() {
// this will NEVER execute, because computeds
// do not work on plain hashes
console.log('hashPropertyComputed triggered');
return JSON.stringify(this.get('hash'));
}),
wrappedHash: Ember.Object.create({r: 5, s: 6}),
hashPropertyComputed: Ember.computed('hash.a', function() {
// this will NEVER execute, because computeds
// do not work on plain hashes
console.log('hashPropertyComputed triggered');
return JSON.stringify(this.get('hash'));
}),
wrappedHashPropertyComputed: Ember.computed('wrappedHash.r', function() {
console.log('wrappedHashPropertyComputed triggered');
return JSON.stringify(this.get('wrappedHash'));
}),
actions: {
updateHash: function() {
let newHash = {x: 8, y: 9};
this.set('hash', newHash);
},
updateHashProperty: function() {
this.set('hash.a', 100);
console.log('updateHashProperty >', this.get('hash'));
},
updateWrappedHashProperty: function() {
this.set('wrappedHash.r', 42);
},
}
});
<h1>Computed properties with hashes</h1>
<br>
<br>
original hash: {a: 1, b: 2}
<br>
hashComputed: {{hashComputed}}
<br>
<button {{action "updateHash"}}>Update hash object</button>
<br>
<button {{action "updateHashProperty"}}>Update hash property</button>
<br>
<br>
wrappedHash: {{wrappedHash.r}} {{wrappedHash.s}}
<br>
wrappedHash: {{wrappedHashPropertyComputed}}
<br>
<button {{action "updateWrappedHashProperty"}}>Update wrapped hash property</button>
<br>
<br>
<hr>
<br>
https://guides.emberjs.com/v2.2.0/object-model/computed-properties-and-aggregate-data/
{{outlet}}
<br>
<br>
{
"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.2.2",
"ember-data": "2.7.0",
"ember-template-compiler": "2.2.2"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment