我需要覆盖Backbone.sync以允许 PUT 问题是我不知道如何以及在何处放置它。
这是我的模特:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var Input = Backbone.Model.extend({
url: 'http://localhost/InterprisePOS/SOP/mobilecreateinvoice/',
initialize: function(){
},
toJSON : function() {
return _.clone({ input:this.attributes });
},
});
return Input;
});
这是我视图中的保存功能:
save: function(){
invoice = new Invoice();
input = new Input();
invoice.set({POSWorkstationID: "POS7"});
invoice.set({POSClerkID: "admin"});
invoice.set({CustomerName: "Alice in Wonderland Tours"});
invoice.set({IsFreightOverwrite: true});
invoice.set({BillToCode: "CUST-000009"});
InvoiceCollection.add( invoice );
//var invoices = JSON.stringify({Invoices: InvoiceCollection.toJSON()});
_.each(this.collection.models, function(cart){
InvoiceDetailCollection.add( cart );
});
input.set({ "Invoices": InvoiceCollection.toJSON() });
input.set({ "InvoiceDetails": InvoiceDetailCollection});
alert( JSON.stringify(input.toJSON()) );
input.save();
}
答案 0 :(得分:7)
默认的Backbone同步处理程序将CRUD映射到REST,如下所示:
有时,较旧的服务器通过使用_method和X-HTTP-Method-Override标头模仿HTTP方法来模拟HTTP。如果是这种情况,您应该将Backbone.emulateHTTP
设置为true
如果您想要自定义映射,那么您需要覆盖Backbone.sync。覆盖的示例可能如下所示:
Backbone.sync = function(method, model, options, error) {
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
options = {
success: options,
error: error
};
}
var resp = function(resp) {
if (resp.status) {
options.success(method != 'read' ? model : resp.data);
}
else {
options.error('Record not found ' + resp.data);
}
};
var store = model.customStorage || model.collection.customStorage;
switch (method) {
case 'read': model.id ? store.read({id: model.id}, resp) : store.readAll(resp); break;
case 'create': store.create(model.attributes, resp); break;
case 'update': store.update(model.attributes, resp); break;
case 'delete': store.delete(model.id, resp); break;
}
};
如果customStorage是您的实现,它可能是您想要的任何尊重我创建的方法。前段时间,我为HTML5 WebSQL Storage创建了一个骨干同步覆盖,它是开源的,位于GitHub上https://github.com/mohamedmansour/backbone.webStorage
我希望这有助于您入门!祝你好运!