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

时间:2011-10-31 15:12:52

标签: 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;
}

这是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);
},

2 个答案:

答案 0 :(得分:7)

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

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

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

答案 1 :(得分:1)

我想我弄清楚这里出了什么问题。而Brian你说得对,它与Backbone.save调用的异步特性有关。问题是我正在使用DEBUGGER。这将停止所有执行。我实际上并不真正理解异步调用是如何工作的,也许是线程?我假设在我调出“保存”然后等待一秒之后,“保存”调用的异步部分(无论是什么)将在后台执行。但这种情况并非如此。调试器会停止一切。所以'save'中的options.success闭包总是在单步执行'save'后被调用。简而言之,这一切都是由于我不能正确理解javascript和javascript调试。