gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:28:55 24 4
gpt4 key购买 nike

我在我的模型上调用“保存”并在我的 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);
},

最佳答案

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

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

当您继续并且事件循环从服务器获得响应(这可能是几分之一秒,也可能是几秒)之后,您的值将被设置。

关于backbone.js - Backbone.Model.save 没有使用服务器响应设置我的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7955629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com