Javascript 无法覆盖主干保存成功处理程序
Im使用主干网1.1.0。我已经有一段时间没有使用主干了,但我确信我过去能够轻松地覆盖save方法的成功处理程序。然而,现在我似乎无法做到这一点!我的代码是:Javascript 无法覆盖主干保存成功处理程序,javascript,backbone.js,Javascript,Backbone.js,Im使用主干网1.1.0。我已经有一段时间没有使用主干了,但我确信我过去能够轻松地覆盖save方法的成功处理程序。然而,现在我似乎无法做到这一点!我的代码是: model.save({}, { successs: function() { console.log('in my custom success handler'); } }); 我的自定义处理程序不执行,而默认的成功处理程序执行,从而触发sync事件 我已经研究了这个问题并尝试了每一种
model.save({}, {
successs: function() {
console.log('in my custom success handler');
}
});
我的自定义处理程序不执行,而默认的成功处理程序执行,从而触发sync
事件
我已经研究了这个问题并尝试了每一种解决方案,但没有一种有效。其中包括在第三个参数处传入success handler对象、在第二个参数处传入null作为第一个参数等
模型保存方法的主干库代码(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/怎么可能覆盖成功处理程序(我确信我以前能够做到),因为当您传入成功处理程序时,它会被分配给本地varsuccess
,然后无论如何都会被覆盖:
var success = options.success;
options.success = function(resp) {
....
2/为什么我的处理程序不也执行?应将其分配给本地成功变量:
var success = options.success;
然后在选项中执行。成功:
if (success) success(model, resp, options);
当我通过chrome开发者工具进行调试时,成功是未定义的。但我在网上看到:
var success = options.success;
该
options.success
包含我的客户处理程序方法。然而,本地varsuccess
在某种程度上是未定义的…我认为您的代码应该是:
model.save({}, {
success: function(){
//^-----this-----^
console.log('in my custom success handler');
}
});
我不知道创建此问题时是否输入错误,但您指定了
successs
-该属性中有3个字母s
。您的回调定义也是错误的,它是success:function(){}
,而不是success:function({})
facepalm这就是问题所在。好吧,至少它很简单(但仍然很难发现),祝你的项目好运!