2011-08-01 58 views

回答

0
myModel = new Model id:'model1' 

$.ajax '/urlWhereUWantToSaveModel', 
    type: 'POST' 
    data: myModel.toJSON() 
    dataType: 'json' 
    success: (response) -> 
    // Server response should be json object with an error property if something went wrong 
    if response.error 
     console.log 'save failed' 
    else 
     console.log 'save succeeded' 
    error: -> 
    console.log 'error' 
+0

謝謝你,這是非常有幫助 – user737688

+1

這是CoffeeScript代碼,而不是JavaScript(還) –

3

從以往的經驗,這是更好地收集和模型中顯式調用AJAX,而不是使用一般Sync的。給你更多的靈活性。以下是我們在Planbox中爲待辦事項列表中的任務集合所做的工作。

 
    TaskCollection = Backbone.Collection.extend({ 
    // Get all existing tasks from the server 
    fetch: function(options) { 
     var collection = this; 
     // Remove references to callbacks so that calls further down 
     // don't trigger them again! 
     var onsuccess = options.success; if (options.success) delete options.success; 
     var onerror = options.error; if (options.error) delete options.error; 
     $.ajax({ 
     url: '/get_tasks', 
     type: 'GET', 
     dataType: 'json', 
     success: function(object, status) { 
      collection.refresh(collection.parse(object)); 
      if (onsuccess) onsuccess(collection, object); 
     }, 
     error: function(xhr, status, error) { 
      if (onerror) onerror(collection, xhr.responseText); 
     } 
    } 
    }); 

    TaskModel = Backbone.Model.extend({ 
    // Save a task on the server 
    save: function(options) { 
     var model = this; 
     $.ajax({ 
     url: '/save_task', 
     type: 'POST', 
     dataType: 'json', 
     data: model.toJSON(), 
     success: function(object, status) { 
      if (options.success) options.success(model, object); 
     }, 
     error: function(xhr, status, error) { 
      if (options.error) options.error(model, object.content); 
     } 
    } 
    }); 

    var tasks = new TaskCollection(); 
    tasks.fetch(); 

請注意,我們假定服務器吐出來爲每個任務對象unqiue id屬性。骨幹將使用它來識別模型。所以,你可以這樣做tasks.get(12)與編號12

檢索任務,也注意到Planbox我們對車型更豐富的save功能,如save_statusmove。這使我們能夠靈活地添加更多的預處理和後處理,如驗證和更新細節。

而且我們還擴展了通用Backbone Collection和Model對象來封裝上面的獲取和保存函數。