无法覆盖 Backbone 保存成功处理程序

Cannnot overwrite Backbone save success handler

我正在使用 backbone 1.1.0。自从我使用 Backbone 以来已经有一段时间了,但我确信我曾经能够轻松地覆盖保存方法的成功处理程序。但是,现在我似乎无法做到!我的代码是:

model.save({}, {
    successs: function() {
        console.log('in my custom success handler');
    }        
});

我的自定义处理程序不会执行,而默认的成功处理程序会执行,从而触发 sync 事件。

我查看了问题 here 并尝试了每个解决方案,其中 none 有效。其中包括在第三个参数、第二个参数处传递成功处理程序对象,将 null 作为第一个参数传递等等等等。

模型保存方法的 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;
},

2 件事让我困惑:

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.....

我认为你的代码应该是:

model.save({}, {
  success: function(){
  //^-----this-----^
    console.log('in my custom success handler');
  }        
});