EMBER WORKSHOP: Computed Properties
Computed Properties
by jdcravens
HTML
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://builds.emberjs.com/release/ember.js"></script>
JavaScript
// DOs
// Computed properties let you declare functions as properties
// Use computed properties to build a new property by synthesizing other properties.
// DONTs
// Computed properties should not contain application behavior
// Not cause any side-effects when called.
// DEBATEABLE
// Using Computed properties on Models or Controllers. Since Controllers decorate Models, some believe simple computed properties should be on the Controller, others like them all in one place on the Model.
// Below shows common source of confusion with computed properties and functions as properties
App = Ember.Application.create({});
App.DefaultPlayer = Ember.Object.extend({
init: function () {
this.set('imgProfilePrefix', 'default_');
this.set('imgProfileSuffix', '_profile');
},
name: "Steve", // one way to handle defaults
baseDir: "/images",
imgName: function(){
return this.get('imgProfilePrefix') + this.get('name').split(' ').join('_').toLowerCase() + this.get('imgProfileSuffix') + '.png';
}, // see no property method ... so call is different below
imgPath: function(){
return this.get('baseDir') + '/profile/' + this.imgName();
}.property('baseDir', 'imgName')
});
var steve = App.DefaultPlayer.create({});
console.log(steve.get('imgName')); // returns the function
console.log(steve.imgName());
console.log(steve.get('imgPath'));
var suzie = App.DefaultPlayer.create({
name: "Suzie" // override default
});
console.log(suzie.get('imgPath'));
console.log(suzie.imgName());
// Dynamic updates
suzie.set('baseDir', 'imgs');
console.log(suzie.get('imgPath'));