Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Computed properties
import Ember from 'ember';
import Account from '../models/account';
export default Ember.Controller.extend({
appName:'Ember Twiddle',
name: "",
balance: 0,
totalBalanceInCents: function() {
return this.model.reduce(function(previousValue, account) {
return previousValue + account.get('balanceInCents');
}, 0);
}.property('model.@each.balanceInCents'),
totalBalance: function() {
return this.get('totalBalanceInCents') / 100;
}.property('totalBalanceInCents'),
actions: {
createAccount() {
this.store.createRecord('account', {
name: this.get('name'),
balance: this.get('balance')
});
}
}
});
import Ember from 'ember';
export default Ember.Route.extend({
init: function() {
this.store.push({
data: [{
id: 1,
type: 'account',
attributes: {
name: 'Test account',
balanceInCents: 1000
},
relationships: {}
}, {
id: 2,
type: 'account',
attributes: {
name: 'Test account 2',
balanceInCents: 5000
},
relationships: {}
}]
});
},
model: function() {
return this.store.peekAll('account');
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<table>
<tr>
<th>Name</th>
<th>Balance</th>
</tr>
{{#each model as |account|}}
<tr>
<td>{{account.name}}</td>
<td>{{account.balance}}</td>
</tr>
{{/each}}
<tr>
<th>Total</th>
<th>{{totalBalance}}</th>
</tr>
</table>
<br>
<br>
<form id="new_account" {{action "createAccount" on="submit"}}>
<label for="name">Name</label>
{{input value=name placeholder="Name"}}
<label for="name">Balance</label>
{{input value=balance placeholder="0"}}
<input type="submit" value="Create Account" />
</form>
{{outlet}}
<br>
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
balanceInCents: DS.attr('number', { defaultValue: 0 }),
balance: Ember.computed('balanceInCents', {
get(key) {
var cents = this.get('balanceInCents');
Ember.debug("Cents: " + cents);
var dollars = cents / 100;
Ember.debug("Dollars: " + dollars);
return this.get('balanceInCents') / 100;
},
set(key, value) {
var cents = value * 100;
Ember.debug("Setting balance, cents: " + cents);
this.set('balanceInCents', cents);
return value;
}
}),
balanceInCentsChanged: Ember.observer('balanceInCents', function() {
console.log("balanceInCents changed to: " + this.get('balanceInCents'));
})
});
{
"version": "0.4.16",
"EmberENV": {
"FEATURES": {}
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "https://cdnjs.cloudflare.com/ajax/libs/ember.js/2.1.0/ember.debug.js",
"ember-data": "https://cdnjs.cloudflare.com/ajax/libs/ember-data.js/2.1.0/ember-data.js",
"ember-template-compiler": "https://cdnjs.cloudflare.com/ajax/libs/ember.js/2.1.0/ember-template-compiler.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment