[英]Creating a custom “sync” method in Backbone.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));
}
});
我遇到的問題是: $.ajax(_.extend(params, options));
似乎覆蓋了我創建的自定義success
和error
函數。 但我也擔心干擾任何自定義回調或其他可能在使用此模型的應用程序中指定的功能。
重寫Backbone的sync()
方法的“正確”方法是什么?
謝謝!
如果您查看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);
};
//...
}
因此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));
BTW,你的model.parse(data);
在你的success
處理程序中可能沒有做任何有用的事情, parse
應該只是一個簡單的過濾器,所以你想要用model.parse(data)
返回值做一些事情(比如model.set
調用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.