2

这基本上是原始问题简化为:

我有一个 Backbone 模型,我想每次save成功执行某个操作,但不是在它完成后执行fetch。在我看来,最干净且干扰最小的方法是将处理程序附加到sync事件并检查 XHR 对象:如果它是对 GET 的响应,则做一件事,如果是 POST,则做另一件事。

但是,看起来我无法确定创建 jqXHR 以响应的 HTTP 方法......或者我可以吗?

4

2 回答 2

2

You can override the Backbone.sync method like this :

var sync = Backbone.sync;

Backbone.sync = function(method, model, options) { // override the Backbone sync

                    // override the success callback if it exists
                    var success = options.success;
                    options.success = function(resp) {
                    if (success) success(model, resp, options);
                        // trigger the event that you want
                        model.trigger(methodMap[method]);
                    };

                    sync.call(this, method, model, options);
                };

methodMap looks like :

var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch':  'PATCH',
'delete': 'DELETE',
'read':   'GET'
}

So in order to catch the GET/POST method all you have to do is :

initialize: function() { // your view initialize
    this.listenTo(this.model, "GET", /* your GET callback */);
    this.listenTo(this.model, "POST", /* your POST callback */);
}
于 2014-02-04T00:39:29.883 回答
0

您可以覆盖该save方法以做任何您想做的事情;像这样的东西:

@MyApp.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->

  class Entities.Model extends Backbone.Model

    save: (data, options = {}) ->
      ## do whatever you need to do ##
      super data, options

然后从这个定义而不是扩展你的模型Backbone.Model,就像这样:

class Entities.MyModel extends App.Entities.Model
于 2014-02-03T21:33:47.733 回答