创建的jqxhr
这基本上是原始问题减少到:
我有一个骨干模型,我想每次成功执行save
D时执行某个操作,但不是在fetch
ED之后。如我所见,最干净,最不动感的方法是将处理程序附加到sync
事件并检查XHR对象:如果是对GET的响应,请执行一件事,另一件事是帖子。
但是,看起来我无法确定http方法是根据...或可以?
您可以覆盖backbone.sync方法:
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
看起来像:
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
}
因此,要捕获GET/POST方法,您要做的就是:
initialize: function() { // your view initialize
this.listenTo(this.model, "GET", /* your GET callback */);
this.listenTo(this.model, "POST", /* your POST callback */);
}
您可以覆盖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