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

时间:2012-03-29 02:45:24

标签: javascript backbone.js underscore.js requirejs

我需要覆盖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();
}

1 个答案:

答案 0 :(得分:7)

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

  • 创建→POST /集合
  • 阅读→GET / collection [/ 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;
  }
};

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

我希望这有助于您入门!祝你好运!