How to create nested Ember.js Objects
HTML
<script src="https://github.com/downloads/emberjs/ember.js/ember-0.9.7.1.js"></script>
<script type="text/x-handlebars">
{
{#with App.controller
}
}
< h1 > Account {
{
content.id
}
}: {
{
content.name
}
} < /h1>
<ul>
{{#each filteredPositions}}
<li>{{symbol}}: {{quantity}}</li > {
{
/each}}
{{/with
}
} < /ul>
</script>
JavaScript
window.App = Em.Application.create();
App.jsonObject = {
id: 1812,
name: 'Brokerage Account',
positions: [{
symbol: 'AAPL',
quantity: 300
}, {
symbol: 'GOOG',
quantity: 500
}]
};
App.account = Ember.Object.create(App.jsonObject);
App.controller = Ember.Object.create({
contentBinding: 'App.account',
filteredPositions: function () {
var pos = Ember.getPath(this, 'content.positions');
return pos.filter(function (item, index, self) {
// Only show even indexes (0,2,4,ect)
if (!(index % 2)) {
return true;
}
});
}.property('content.positions.@each').cacheable(),
// This will be called when your positions array's length changes
contentDidChange: function (target, property, value) {
console.log('property:' + property + '\nvalue:' + value);
}.observes('content.positions.length')
});
setTimeout(function () {
// this works just fine!
App.account.set('name', 'Brokerage Account 1');
// does not add new position to UI
App.account.get('positions').pushObject({
symbol: 'MSFT',
quantity: 200
});
}, 2000);