Here’s a little bit of CoffeeScript, but feel free to answer in JavaScript:
model = new MyModel content: content model.save() @collection.add model
Elsewhere, a view is listening for the add
event on the collection:
_addOne: (model, collection, options)=> view = new MyView model: model @subviews[model.id] = view
Sometimes the model hadn’t finished talking to the server, so it didn’t have an id
and this code failed to do what was wanted. So, I wrapped the save
in a promise using the when.js library (when
is mapped to When
here)
When model.save() .then => @collection.add model
Now all is hunky dory with the world. What I’m wondering is, is there a way to get the then
into the _addOne
method, because that’s the bit that’s really waiting, the collection itself doesn’t mind getting a half-baked model added to it.
How can I proceed?
Advertisement
Answer
Use Collection#create
instead:
createcollection.create(attributes, [options])
Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. […] Pass
{wait: true}
if you’d like to wait for the server before adding the new model to the collection.
So if you do this:
@collection.create( { content: content } { wait: true } )
Then the model won’t be added to the collection until the server has responded and the model will have its server-supplied id
by then.