在Backbone.js中创建自定义"sync"方法

Chr*_*row 6 javascript backbone.js underscore.js

sync()在骨干网中创建自定义方法.

我想这样做"正确"并尽可能少地干扰Backbone的正常功能.

这是我到目前为止的代码:

var CustomSyncModel = Backbone.Model.extend({
    sync:function(method, model, options){
        var params = {
            type: 'POST'
            url: model.url(),
            error: function(jqXHR, textStatus, errorThrown){
                alert('error');
            },
            success: function(data, textStatus, jqXHR){
                model.parse(data);
            }
        };
        // Got this from line 1359 in Backbone.js developement library
        //     version 0.9.2:
        $.ajax(_.extend(params, options));
    }
 });
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是:行$.ajax(_.extend(params, options));似乎覆盖了我创建的自定义successerror函数.但我也担心干扰任何自定义回调或其他可能在使用此模型的应用程序中指定的功能.

重写Backbone sync()方法的"正确" 方法是什么?

谢谢!

mu *_*ort 8

如果你看一下Model#fetch你会看到Backbone使用的常用方法:

fetch: function(options) {
  //...
  var success = options.success;
  options.success = function(resp, status, xhr) {
    if (!model.set(model.parse(resp, xhr), options)) return false;
    if (success) success(model, resp);
  };
  //...
}
Run Code Online (Sandbox Code Playgroud)

因此Backbone只是用一个调用原始函数的新函数替换了该函数.在你的情况下,你会有这样的事情:

// We don't own options so we shouldn't modify it,
// but we can do whatever we want to a clone.
options = _(options).clone()

// Replace options.error with a wrapper.
var error = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
    alert('error');
    if(error)
        error(jqXHR, textStatus, errorThrown);
};

// Replace options.success with a wrapper.
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
    model.parse(data);
    if(success)
        success(data, textStatus, jqXHR);
};

// We don't need error or success in here anymore.
var params = {
    type: 'POST',
    url:   model.url() 
};
$.ajax(_.extend(params, options));
Run Code Online (Sandbox Code Playgroud)

顺便说一下model.parse(data);,你的success处理程序可能没有做任何有用的事情,parse应该只是一个简单的过滤器,所以你想要做一些model.set带有model.parse(data)返回值的事情(比如一个调用).