Question

I've been working on an EmberJS application for about a week now, and have written my own localStorage adapter for EmberJS/Data to allow for data persistence. The app is a small note-taking application. Ideally, I'd like to have a Notebook model that has many Note models associated with it.

However, I haven't found a way to do this that results in a mutable array. While you can "implement" a hasMany relation...

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)
});

...the ModelArray created by the hasMany method is immutable in EmberJS. It appears that this is currently being worked on - there is an "associations" branch of EmberJS/Data here - but modifying the ModelArray is critical to this application, to i.e. create a new Note:

var notebook = Noted.store.createResource(Noted.Notebook, {
  title: "Foo Notebook"
});
notebook.get("notes").pushObject(Noted.store.createResource(Noted.Note, {
  title: "Bar Note",
  note_text: "Blah blah blah."
}));
notebook.get("notes").objectAt(0).get("title") //returns undefined

Although the very latest commit of EmberJS/Data does include array mutability, it still lacks any sort of observation - the adapter isn't notified when changes are made, and they are not saved.

I'm wondering: what's the best alternative to a hasMany association until this ability is added to EmberJS/Data? I've been looking into different patterns, such as having a note IDs array in the Notebook model with some sort of fetch/retrieve interface to go with it, but I've gotten absolutely nowhere. I've spent quite a good chunk of today trying to figure out the best way to do this, and all I have is a lot of frustration.

Was it helpful?

Solution

Ember-data will get there eventually. Until then, I currently just mutate the array and manually call all of the corresponding store methods to reflect the mutation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top