我需要覆盖backbone.sync以允许PUT方法

jon*_*aag 2 javascript requirejs backbone.js underscore.js

我需要覆盖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;
});
Run Code Online (Sandbox Code Playgroud)

这是我视图中的保存功能:

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();
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*our 7

默认的Backbone同步处理程序将CRUD映射到REST,如下所示:

  • 创建→POST /集合
  • 阅读→GET /集合[/ id]
  • 更新→PUT/collection/id
  • 删除→DELETE/collection/id

有时,较旧的服务器通过使用_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;
  }
};
Run Code Online (Sandbox Code Playgroud)

在customStorage是您的实现的地方,它可能是您想要的任何尊重我创建的方法.前段时间,我为HTML5 WebSQL Storage创建了一个骨干同步覆盖,它是开源的,位于GitHub上https://github.com/mohamedmansour/backbone.webStorage

我希望这可以帮助你开始!祝好运!