3

我正在使用该create方法将模型添加到集合中,并且 api 响应很好。该模型似乎已正确返回,并查看console.dir( resp );我正在寻找的模型。但是,当我尝试访问定义为runningorderid的时,响应为空。我认为这与响应的异步性质有关,但我不知道如何处理它。ididAttribute

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

问题截图

4

2 回答 2

2

collection.create,与所有与服务器请求相关的方法一样,确实是异步的。在您的情况下,您可以收听同步事件以获得所需的结果。

来自http://backbonejs.org/#Collection-create

一旦在服务器上成功创建模型,创建模型将立即触发集合上的“添加”事件以及“同步”事件。

例如:

resp.on('sync', function(model) {
  console.dir( resp );
  console.dir( resp.get("strt") );
  console.dir( resp.id );
});
于 2012-07-24T09:54:17.203 回答
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!

于 2012-07-24T09:57:12.750 回答