开发者

Best way to trigger filters for Backbone.js collection

Hi all I am creating my first Backbone.js app. It is basically a collection that renders the data in a table. What I want to do is to be able to filter and sort data. What is the best way to do it? Should I use the Router or store some params that render will take into consideration.

开发者_开发技巧

I think the Router will get really complex soon as I am going to have 3-4 filters and 1 order option.

What do you think?


In my backbone-based project, I've subclassed Backbone.Collection to allow Controller to add arbitrary GET parameters to it.

Here is a snippet for you:

RailsCollection = Backbone.Collection.extend({
  initialize: function() {
    _.bindAll(this, 'url');
  },

  url: function() {
    var base = this.baseUrl || this.model.prototype.baseUrl;

    if(!this.params) {
      return base;
    } else {
      return base + '?' + $.param(this.params);
    }
  }
});


I would add methods on my collections for the filtering and sorting, and using a view to just render an arbitrary collection, that might be filtered or ordered.

For ordering there is a built in hook: http://documentcloud.github.com/backbone/#Collection-comparator

For filtering, check out the underscore helper methods on collections, and extend with your own.

You could for example have a collection.doFiltering([filter1, filter2, filter3]); that returns a filtered array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜