2011-05-10 57 views
16

這似乎是一個明顯的,但我有點想念它...backbone.js collection get vars

你如何發送options和backbone.js集合fetch()?

或者從更廣泛的角度來看:我在服務器上有一個很大的數據集,在這種情況下,我想通過一個集合來訪問這些數據集。看到可能有成千上萬條消息,我不想一次性獲取並存儲所有消息,因此我的收藏必須至少了解限制和偏移量。更不用說查詢過濾或排序的列表。

即使是處理這個問題的方法,骨幹集合是什麼?

乾杯

回答

31

我一直在搞亂骨幹幾天,我不得不幾乎立即處理這個問題,我看着這個解決方案,但我發現它笨重。在閱讀了更多的骨幹文檔後,我發現你實際上可以覆蓋fetch()方法中的任何jQuery.ajax選項。因此,例如

Posts = Backbone.Collections.extend({ 
    model: Post, 
    url: '/posts' 
}); 

現在,當你想調用fetch時,只需發送你想要的任何參數。例如

var posts = new Posts(); 
posts.fetch({ data: { page: 3, pagesize: 10, sort: 'asc' } }); 

這將產生以下請求:

http://yourdomain/posts?page=3&pagesize=10&sort=asc 

不管怎樣,我知道你已經接受了答案,但希望這會幫助別人。

0

覆蓋您的收藏的 「網址」 功能,並添加參數(?PARAM = XYZ)。

也可以使用fetch的options參數,因爲它是傳遞給最終jQuery ajax調用的參數。所以如果你添加一個「數據」參數,它將被使用。

1

您可以將一個ID添加到服務器可用於選擇數據發送的URL。例如。

var EventsCollection = Backbone.Collection.extend({ 

     model: Events, 

    }); 

    var eventCollection = new EventsCollection(); 
    eventsCollection.url = 'foo?offset=10&limit=20'; 
    eventsCollection.fetch(); 
6

考慮一下這段代碼,當你實例化你的集合時,你傳遞偏移量,限制或排序的首選項。如果沒有提供首選項,初始化將採用默認值。然後url函數將這些附加到對服務器的調用中。之後,在處理來自服務器的響應時,您將不得不更新這些值(可能只是偏移量)。

MessageList = Backbone.Collection.extend({ 

    initialize: function(models, options) { 
     options || (options = {}); 
     this.offset = options.offset || 0; 
     this.limit = options.limit || MessageList.DEFAULT_LIMIT; 
     this.sortBy = options.sortBy || MessageList.DEFAULT_SORTBY; 
    }, 

    url: function() { 
     return '/messages?' + 
       'offset=' + encodeURIComponent(this.offset) + '&' + 
       'limit=' + encodeURIComponent(this.limit) + '&' + 
       'sort_by=' + encodeURIComponent(this.sortBy); 
    }, 

    parse: function(response) { 
     // Parse models 
     // Parse offset, limit, sort by, etc 
    } 

}, { 

    DEFAULT_LIMIT: 100, 
    DEFAULT_SORTBY: 'name_asc' 

});