2012-03-29 34 views
2

我需要覆蓋Backbone.sync允許PUT問題是我不知道如何以及在哪裏放它。我需要覆蓋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(); 
} 

回答

7

缺省骨幹同步處理程序映射CRUD休息如下所示:

  • 創建→發佈/收集
  • 閱讀→GET/coll撓度[/ ID]
  • 更新→PUT /收集/ ID
  • 刪除→DELETE /收集/ ID

有時舊服務器仿效HTTP通過模仿與_method和X-HTTP-方法 - HTTP方法覆蓋標題。如果是這樣,你應該設置Backbone.emulateHTTP爲真

如果你想自定義映射,那麼你將需要覆蓋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存儲創建了一個骨幹網同步覆蓋,它位於GitHub上的開源代碼https://github.com/mohamedmansour/backbone.webStorage

我希望這可以幫助您開始!祝你好運!

+0

等待。我應該在哪裏編輯以覆蓋backbone.sync?我應該怎樣稱呼它呢?謝謝 – jongbanaag 2012-03-29 03:06:43

+0

您正在更換'Backbone.sync',注意「Backbone.sync =」,所以您應該在包含Backbone庫之後放置它。 – 2012-03-29 03:10:21

+0

對不起,但我只想澄清。因爲put已經啓用。是否有必要重寫backbone.sync?如果我想使用PUT,我可以使用這樣的東西嗎?我怎麼稱呼它? – jongbanaag 2012-03-29 03:17:39