Sideloading funniness
The latest build of Ember.
HTML
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://builds.emberjs.com/ember-latest.js"></script>
<script src="http://builds.emberjs.com/tags/v1.0.0-beta.4/ember-data.prod.js"></script>
<script type="text/x-handlebars" data-template-name="index">
<h1>{{name}}</h1>
<p>
<button {{action "addToy"}}>Add Toy</button>
</p>
<h2>Toys:</h2>
<ul>
{{#each toys}}
<li>{{name}}</li>
{{/each}}
</ul>
<div class="store">
<h2>DS.Store</h2>
<p>
DS.Store has: {{storeToysLen}} toys
</p>
<ul>
{{#each storeToys}}
<li>{{id}} - {{name}}</li>
{{/each}}
</ul>
</div>
</script>
CSS
body { margin: 10px; }
h1, h2, p, ul { margin: 7px 0; }
h1 { font-size: 1.5em; font-weight: bold}
h2 { font-size: 1.2em; font-weight: bold}
ul { padding: 0 0 0 25px; }
ul li { list-style-type: disc; }
.store { background: #eee; border: 1px solid #666; color: #444; padding: 5px; margin: 50px 10px; }
JavaScript
App = Ember.Application.create({});
//
// Define models
//
App.Child = DS.Model.extend({
name: DS.attr('string'),
toys: DS.hasMany('toy'),
});
Ember.Inflector.inflector.irregular("child", "children");
App.Toy = DS.Model.extend({
name: DS.attr('string'),
quantity: DS.attr('number')
});
//
// Main Program
//
App.IndexRoute = Em.Route.extend({
model: function(){
return this.store.createRecord("child", {
'id': childID,
'name': childName
});
},
setupController: function(controller, model){
controller.set('content', model);
}
});
App.IndexController = Em.ObjectController.extend({
content: null,
storeToys: function(){
return this.store.all('toy');
}.property(),
storeToysLen: Em.computed.alias('storeToys.length'),
actions: {
// Add a toy to the child
addToy: function(){
var self = this,
store = this.get('store'),
child = this.get('content'),
toy = nextToy();
// Create toy and add it to the child
toy = store.createRecord('toy', {
'name': toy.name,
'quantity': toy.quantity
});
// Save the new toy
toy.save();
}
}
});
//
// Mock a database and web service
//
var childID = 0,
childName = 'Ben',
toys = [];
// Toy names to cycle through
var toyNameIndex = 0,
toyNames = [
'car',
'doll',
'teddy bear',
'xbox',
'action figure',
'bike',
'scooter'
];
// Add a toy to the list
function nextToy() {
if (toyNameIndex >= toyNames.length) {
toyNameIndex = 0;
}
var name = toyNames[toyNameIndex++],
id = toys.length,
toy = {
'id': id,
'name': name,
'quantity': 1
};
toys.unshift(toy);
...