How To Re Fetch Backbone Collection After Collection Create?
Solution 1:
This is because the request sent to the server when you call Collection.create
is asynchronous, the Javascript code will continue to execute before the server receives and responds to the request.
If you want to have the Model updated with the ID coming back from the server, you can specify {wait: true}
in the Collection.create
call. This will mean that the Collection will not have the Model added straight away, but instead only when the server responds (successfully).
In this case you should not run the fetch
immediately afterwards, as it will also need to wait for the create operation to complete. You should setup any following actions to trigger when the create operation has completed. Here is an example:
var model = collection.create({field: 'abc'}, {wait: true});
model.once('sync', function() { window.alert(model.id); });
Solution 2:
Backbone's create
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.
There's no need to fetch a collection after a create, the model id
and any other field are automatically merged within its attributes
hash.
Fetch after model creation
While mikeapr4 is not wrong, his example could be improved.
The { wait: true }
is unnecessary if the only problem comes from the fetch, not from the model already being inside the collection.
Also, once
should be avoided as it's the "old" way, and instead listenToOnce
should be used. See Difference between ListenTo and on.
If you really want to fetch once a model is created, using events is overkill here, and instead, using the success callback is best:
save: function() {
// ..snip...this.model.shifts.create({ /* ...snip... */ }, {
context: this,
success: this.onModelCreated
});
},
onModelCreated: function() {
// the model is now created and its attributes are up-to-datethis.model.shifts.fetch();
}
Other notes on your code
There are no sync
option in Backbone. Only a "sync"
event and a sync
function.
Avoid using the global jQuery selector (like $('.class-name')
) and instead, whenever the element is within the view's element, use this.$('.class-name')
.
Also, cache the jQuery element to avoid the costly search of the find
method.
Like $("#start")
could be cache and reused. Only reset the cached elements when re-rendering.
The Backbone .render
function should return this
by convention.
Then, your rendering call should look like:
this.$container.html(this.render().el); // el is enough
Post a Comment for "How To Re Fetch Backbone Collection After Collection Create?"