Backbone.Model.save没有使用服务器响应设置我的模型

Nic*_*ang 4 backbone.js

我在我的模型上调用'save'并在我的PHP后端将新模型作为json返回.当我逐步完成Backbone.Model.save方法时,我可以看到它成功获取服务器响应,然后设置模型(在下面的options.success闭包中).但是当执行返回到我的单击处理程序时,模型具有旧属性(即,未设置id).可能会发生什么?

这是我的点击处理程序:

addButtonClick: function(e) {
  var data = $(e.target).closest('form').serializeObject();
  var p = new Domain.Page; // this extends Backbone.Model
  p.set(data);
  p.save();
  // ****
  // **** AFTER p.save, the model p still has the OLD ATTRIBUTES... why??
  // ****
  return false;
}
Run Code Online (Sandbox Code Playgroud)

这是Backbone的保存方法:

// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save : function(attrs, options) {
  options || (options = {});
  if (attrs && !this.set(attrs, options)) return false;
  var model = this;
  var success = options.success;
  options.success = function(resp, status, xhr) {
    // ****
    // **** NEXT LINE SUCCESSFULLY SETS THE MODEL WITH THE SERVER RESPONSE
    // ****
    if (!model.set(model.parse(resp, xhr), options)) return false;
    if (success) success(model, resp, xhr);
  };
  options.error = wrapError(options.error, model, options);
  var method = this.isNew() ? 'create' : 'update';
  return (this.sync || Backbone.sync).call(this, method, this, options);
},
Run Code Online (Sandbox Code Playgroud)

Bri*_*sio 7

save方法是异步的.换句话说,model.set内部调用save发生在服务器响应之后.

你问为什么在save调用之后值立即相同.答案是:在那个时间点,您的代码尚未收到响应.没有调用回调. model.set没有被称为.

继续操作并且事件循环从服务器获得响应(这可能只是几秒钟,可能是几秒钟),您的值将被设置.