2012-04-26 25 views
1

看起來在我調用backbone.js集合時,它通過cookie傳遞id而不是平穩傳遞給我的GET方法。在請求標題它是這樣來的:使用Backbone.Collection.get(id)安靜地

Cookie:posts = ag5kZXZ-c29jcmVuY2h1c3IOCxIIUG9zdExpc3QYAQw; dev_appserver_login = 「[email protected]:錯誤:114323764255192059842」

這是我有:

get調用:

postCollection.get(id) 

和get方法:

def get(self, id): 

我想在get方法中使用id而不是必須使用cookie。

+2

您想使用'fetch'從遠程服務器檢索項目。 'get'返回集合中已有的特定模型。它會通過URL自動完成 - 你必須不做任何事情。 – tkone 2012-04-26 20:29:51

+0

我想得到一個特定的模型,如果它不存在,我希望我的數據庫添加該模型。我只是無法弄清楚如何讓我的客戶端正確地將我的ID發送到我的服務器。 – prashn64 2012-04-26 20:42:52

回答

5

可能最好的方法來完成這個是類似於以下內容。

var model = collection.get(id); 
// If the model is not present locally.. 
if (!model) { 
    // Add empty model with id. 
    model = collection.add([{id: id}]); 
    // Populate model attributes from server. 
    model.fetch({success: successCallback, error: errorCallback }); 
} 

collection.get(id)不應該向後端發出請求。

+1

如果它不在集合中,它將不得不被檢索,並且因此將涉及實際查看模型的某種回調(並且還需要針對失敗)。或者,如果您使用的是jQuery,您可以讓該方法返回一個承諾對象,最終可以使用該模型解決或拒絕。 – JayC 2012-04-26 21:27:10

+0

我實際上有點好奇如何'collection.add([{id:id}]);'與這工作,現在我想起它... – JayC 2012-04-26 21:28:49

+1

'model.fetch'支持回調。我已經更新了示例以包含它們。 'collection.add'通過傳遞給它的屬性爲集合添加一個新模型。在這種情況下,'id'是唯一的屬性,其餘的都在服務器上。 'id'必須存在,以便'model.fetch'知​​道要執行HTTP GET/resource/id'請求。 – abraham 2012-04-26 22:06:20

1

這是另一個需要考慮的問題。而不是創建一個大部分爲空的模型,然後在獲取後從服務器向其添加屬性,您可以執行下面粘貼的內容。有一件事要考慮上面的例子,如果你創建了一個模型,然後試圖從服務器獲取這個ID並且它不存在,你就必須清理它。下面的代碼將爲您節省下一步。

myModel = Backbone.Model.extend({ 
    url : function() { 
    /* 
    create _ POST /model 
    read _ GET /model[/id] 
    update _ PUT /model/id 
    delete _ DELETE /model/id 
    */ 
    return this.id ? '/model/' + this.id : '/model'; 
    }, 
}); 


myCollection = Backbone.Collection.extend({ 
    model: myModel, 
    url: function() { 
    return '/model'; 
    }, 
    comparator: function(model) { 
    return model.get("foo"); 
    }, 
    getOrFetch: function(id) { 
    var model = this.get(id) || this.getByCid(id); 
    if (model) return model; 
     var url = this.url() +"/"+ id 
     return new this.model().fetch({url:url}); 
    } 
}); 



var mc = new myCollection(new myModel({foo:"bar"})); 
mc.getOrFetch(1)