-1
使用骨干网1.1.0。自从我使用Backbone以来,它已经有一段时间了,但我确定我曾经能够轻松地覆盖保存方法的成功处理程序。但是,现在我似乎无法做到!我的代码是:无法覆盖Backbone保存成功处理程序
model.save({}, {
successs: function() {
console.log('in my custom success handler');
}
});
我的自定义处理犯规不执行,默认的成功处理程序,触发sync
事件。
我看了一下here这个问题,并尝试了各种解决方案,但都没有成功。这些包括传递成功处理程序对象在第三参数,第二参数,并传递零作为第一个参数等等等等等等
的骨干库代码(V1.1.0),用于模型保存方法是:
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = _.extend({validate: true}, options);
// If we're not waiting and attributes exist, save acts as
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !options.wait) {
if (!this.set(attrs, options)) return false;
} else {
if (!this._validate(attrs, options)) return false;
}
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
两件事困扰我:
1 /怎么可能永远都没有可能改写成功处理程序(我敢肯定,我曾经是能够做到这一点),因为当你在成功处理程序传递,它得到一个分配给本地变种success
,然后覆盖:
var success = options.success;
options.success = function(resp) {
....
2 /为什么我的处理程序也不能执行?它应该得到分配给本地succss VAR:
var success = options.success;
,然后在options.success执行:
if (success) success(model, resp, options);
当我通过Chrome开发者工具调试,成功是不确定的。但我可以看到:
var success = options.success;
options.success
包含我的客户处理程序方法。然而,局部变量success
是,不知何故,undefined
....
我不知道这是否是一个错字,同时创造了这个问题,但您指定'成功“ - 在该房产中有3个字母's'。你的回调定义也是错误的,它是'成功:函数(){}',而不是'成功:功能({});' – Mjh
* facepalm *这是问题 – Mark
嗯,至少它是一些相当简单棘手的现货),祝你的项目好运! – Mjh