一千萬個為什麽

搜索

如何使用Backbone.js從服務器獲取模型集合?

我無法弄清楚從服務器到我的Backbone Collection中獲取模型集合的正確方法,假設我不想要DB中的所有模型,而是需要一組模型(由特定模型屬性過濾) 。

我能弄清楚的唯一方法是覆蓋Fetch並使用函數的“options”參數將過濾器定義傳遞給我的Backbone.Sync函數。

有沒有更好的辦法?

最佳答案

3種最常用的設置集合的方法, 是

  1. bootstrapping models in the page, and then loading them with Collection.reset();

    // you can print this trough serverside in your view, (you are bootstrapping these models)
    var bsModels = [{'name': 'name1'},{'name': 'name3'},{'name': 'name2'}];
    
    // in your code you can use that bootstrapped data via the reset method. 
    var myModel = Backbone.Model.extend({});
    var myCollection = Backbone.Collection.extend({
        model: myModel
    });
    myCollection.reset(bsModels);
    
  2. you can use the fetch, but it would load any and all methods, unless you override the fetch method

  3. a third option is to write your own ajax call, fetching the correct amount of models, and using the same technique as in #1, using Collection.reset(data);

轉載註明原文: 如何使用Backbone.js從服務器獲取模型集合?