Question

I am writing an application using backbone + rails.
The application allows users to create tickets, and show these tickets in real-time for all other users using real-time service pusher.

My problem is that when a user creates a ticket I add it to the collection:

addTicket: function( newTicketData ) {
  var newTicket = new app.Ticket( newTicketData );
  this.collection.add(newTicket, {merge: true});
  newTicket.save(null, {
    wait: true,
    success: this.addTicketSuccess,
    error: this.addTicketError
  });
},

The pusher listener code:

channel.bind('new_ticket', function(data) {
  var ticketDataObj = jQuery.parseJSON( data.content );
  app.ticketsView.addTicket(ticketDataObj);
});

In this point the new model has a cid but not an id from the database, which might be obtained in the addTicketSuccess callback. On the other hand, the server sends a pusher signal in the create action which sends the new ticket with its id, but without id.

The result is two different models in the collection which represent the same object, one with cid and other with id. I am aware to the race-condition and looking for nice and robust solution.

Thanks!!!

Was it helpful?

Solution

The cid is a client id and is never send to the server.

When Backbone model save is called successfully the data received from the server are set on the same object, not creating another model.


So your are manually adding the two models to your collection, try to remove this line :

channel.bind('new_ticket', function(data) {
  var ticketDataObj = jQuery.parseJSON( data.content );
  // create a new method addAndMergeTicket
  app.ticketsView.addAndMergeTicket(ticketDataObj);
});

In this new method, before you add the model to the collection, iterate through the collection models and if you find that it already exists don't add it again

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