Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - getting id from collection create

I am adding a model to a collection using the create method and the api is responding just fine. The model seems to have been properly returned and see the console.dir( resp ); which is what I was looking for. However, when I try to access runningorderid, which is the id as defined with idAttribute, the response is null. I presume this is something to do with the async nature of the response, but I don't know how to deal with it.

var resp = window.app.RunningOrderCollection.create(
        { runningorderid: null, listitemid: 1, starttime: n} , 
        { wait: true }
);
console.dir( resp );
console.dir( resp.get("strt") );
console.dir( resp.id );

screenscape of problem

like image 655
Joe Avatar asked Jul 22 '26 12:07

Joe


1 Answers

collection.create, as all methods related to server requests, is indeed asynchronous. In your case, you could listen to the sync event to get the desired result.

From http://backbonejs.org/#Collection-create

Creating a model will cause an immediate "add" event to be triggered on the collection, as well as a "sync" event, once the model has been successfully created on the server.

For example:

resp.on('sync', function(model) {
  console.dir( resp );
  console.dir( resp.get("strt") );
  console.dir( resp.id );
});
like image 74
nikoshr Avatar answered Jul 25 '26 04:07

nikoshr