Ember-data examples
In response to: http://stackoverflow.com/questions/9305403/alternative-to-associations-with-emberjs-data
by ud3323
HTML
<script src="https://github.com/downloads/emberjs/ember.js/ember-latest.js"></script>
<script src="https://github.com/downloads/emberjs/data/ember-data-latest.js"></script>
<script type="text/x-handlebars">
{{#with Noted.notebookController.content}}
Notebook title: {{title}} <br /><br />
{{#each notes}}
Note id: {{id}} <br />
Note title: {{title}} <br />
Note text: {{note_text}} <br /><br />
{{/each}}
{{/with}}
</script>
JavaScript
Noted = Ember.Application.create();
/*
Model layer definition
*/
// Create store
Noted.set('store', DS.Store.create());
// Create Models
Noted.Note = DS.Model.extend({
title: DS.attr('string'),
note_text: DS.attr('string'),
});
Noted.Notebook = DS.Model.extend({
title: DS.attr("string"),
notes: DS.hasMany('Noted.Note')
});
/*
Controller layer definition
*/
Noted.set('notebookController', Ember.Object.create({
content: null
// Add other logic for your notebook here
}));
/*
App logic
*/
// Add a new records to the store
// Pay attention to how the association `notes` is defined
Noted.get('store').load(Noted.Note, {id: 1, title: 'My 1st note', note_text: 'This is a test of the emergency broadcast system...'});
Noted.get('store').load(Noted.Notebook, {id: 1, title: 'My cool Notebook', notes: [1]});
// Lets add in a second note to this notebook
var notebook = Noted.get('store').find(Noted.Notebook, 1);
// First we need to create the new note
var _newNote = Noted.get('store').createRecord(Noted.Note, {id: 2, title: 'Bar Note', note_text: 'Blah blah blah'});
// And then we can add it to the `notes` association
// Since we don't have `embedded: true` on our association we must push the new note's clientId to the association
notebook.get('notes').pushObject(_newNote.get('clientId'));
// Populate the notebookController
Noted.setPath('notebookController.content', notebook);