Backbone.js - getting id from collection create

放肆的年华 提交于 2019-12-07 16:33:01

问题


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 );


回答1:


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 );
});



回答2:


To circumvent the async nature of the server-operations of collections and models, bind the actions to be taken after the operations to the events that are triggered when those operations are finished. For example the backbone.js documentation has the following to say about Collection's create-function:

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. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.

So, you have passed {wait: true}, so the collection will trigger an add event when the model has been created on the server and added to the collection. With this logic:

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

Check out the exellent catalog of events in the backbone.js documentation for more info!

Hope this helps!



来源:https://stackoverflow.com/questions/11628076/backbone-js-getting-id-from-collection-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!