Don't add model immediately in collection backbone.js

Don't add model immediately in collection backbone.js

You may encounter a problem with 'create' function of a collection in backbone wherein a model is directly being added to the collection without success or failure.

Let's take a general scenario. You want to create a customer record in a database and want to make it visible if it gets successfully inserted there.

sample code :

customers.create(customer, { silent: true,
 success: function(collection, response){
  console.log('success');
 },
 error: function(){
  console.log('error');
 } 
}); 

This code will add the customer record without checking whether it is success or not at back end.

How to overcome this issue ?

All you need to do is add an attribute "wait = true" to create function above. This will wait for success or error functions to be executed and add the model/record to collection if it is a success

below is example:

session.requests.create(request, { silent: true, wait: true,
 success: function(collection, response){
  console.log('success');
 },
 error: function(){
  console.log('error');
 } 
}); 

Also if you want to add model to specific index use "at" attribute.

session.requests.create(request, { silent: true, wait: true, at: 0,
 success: function(collection, response){
  console.log('success');
 },
 error: function(){
  console.log('error');
 } 
});
Lakshay Katney Avatar

Lakshay Katney

Saleforce developer by profession but I like to work with various technologies.I blog about Force.com, Hybrid Apps, PhoneGap, AngularJS, BackboneJS, JavaScript in general. I am Angular & NodeJS fan.

Read More
Share this page
Top 15 Posts