我使用骨干1.1.0。自从我使用Backbone以来已经有一段时间,但我确信我曾经能够轻松覆盖save方法的成功处理程序。但是,现在我似乎无法做到!我的代码是:
model.save({}, {
successs: function() {
console.log('in my custom success handler');
}
});
我的自定义处理程序不执行,默认成功处理程序执行,触发sync
事件。
我查看了问题here并尝试了各种解决方案,其中没有一个有效。这些包括在第三个参数传递成功处理程序对象,第二个参数,传入null作为第一个参数等等等。
Model保存方法的Backbone库代码(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 /怎么可能覆盖成功处理程序(我确信我曾经能够这样做),因为当你传入成功处理程序时,它会被分配给一个本地var {{ 1}},然后覆盖:
success
2 /为什么我的处理程序也不执行?它应该被分配给本地succss var:
var success = options.success;
options.success = function(resp) {
....
然后在options.success中执行:
var success = options.success;
当我通过chrome开发人员工具进行调试时,成功是未定义的。但我可以看到:
if (success) success(model, resp, options);
var success = options.success;
包含我的客户处理程序方法。然而,局部变量options.success
在某种程度上是success
....
答案 0 :(得分:1)
我认为你的代码应该是:
model.save({}, {
success: function(){
//^-----this-----^
console.log('in my custom success handler');
}
});