2012-02-23 48 views
0

在我的Backbone應用程序中,我的集合中有很多排序方法,當基於集合呈現視圖時,我當前正在使用通過路徑的全局變量集(我使用全局變量其他操作添加到集合中,我希望使用最後的順序)。例如主幹路由 - 排序和過濾

routes : { 
    "" : "index",   
    '/ordering/:order' : 'ordering' 
}, 
ordering : function(theorder) { 
    ordering = theorder; 
    listView.render(); 
}, 

然後在我看來

if (typeof ordering === 'undefined') { 
    d = this.collection.ordered();   
} 
else if(ordering == 'owners') { 
    d = this.collection.owners(); 
} 

_.each(d, function(model){   
    model.set({request : self.model.toJSON()}); 
    var view = new TB_BB.OfferItemView({model : model}); 
    els.push(view.render().el); 
}); 

凡訂購和業主是2種排序方法。

所以我的第一個問題是,基於路線,有人可能會建議更好的實現方法嗎?這個視圖在多個地方呈現,因此我使用全局而不是將有序的var傳遞給方法?

第二個問題是 - 我想也添加一些過濾,所以可以說我想按'價格'排序,但也做一些過濾(可以說多個類別ID)。我怎麼能添加一個靈活的'路線'來處理過濾。

我想我能做到

routes : { 
    "" : "index", 
    '/ordering/:order/:filter1/:filter2' : 'ordering' 
}, 

所以過濾器1和過濾器2將是後續的濾波,但如果過濾器可能是0或100這是不行的。有誰能提供解決方案嗎?

回答

3

那麼,首先您應該使用Backbone的內置功能來自動排序集合。您可以通過在集合上定義comparator函數來利用此功能。這爲您提供了各種各樣的開箱即用功能 - 例如,根據您的comparator,收藏會在每次添加或刪除某些東西時自行重新排序。如果要定義多個排序功能,只需將它們全部定義爲函數,然後在需要時更新comparator。那麼你可以溝通那個醜陋的全球var

對於第二個問題,我不完全確定你的意思是「如果過濾器可能是0或100,這將無法工作。」如果你的意思是你會遇到麻煩,如果你不指定所有的過濾器,那是真的。但是你可以使用通配符來解決這個問題。以下是可能的樣子:

// your routes look like this: 
routes : { 
    '/ordering/:order/filters/*filters' : 'ordering' // your routes will look like: /ordering/price/filters/filter_one/filter_two/filter_three 
}, 
ordering: function (order, filters) { 
    filters = filters.split('/'); // creates an array of filters: ['filter_one', 'filter_two', 'filter_three'] 
    listView.render(filters); // pass your filters to the view 
} 

// listView.render() looks like this: 
render: function(filters) { 
    collection = this.collection; 
    _.each(filters, function (filter) { 
    collection = collection.filter(function() { 
     // your actual filtering code based on what the filter is 
    }); 
    }); 
} 
+0

非常感謝Josh,比較器似乎正是我所需要的!過濾也一樣! – Xrender 2012-02-24 08:33:22