Skip to content Skip to sidebar Skip to footer

Filtering The Collection Doesn't Work

I have a collection of models with boolean value interviewed and I want to filter them so that my view would display either models with this property set to true or models with thi

Solution 1:

You're returning a successfully filtered collection, and then not doing anything with them.

showActive: function () {
    this.collection.filterActive();//returns a value you're not usingthis.render();
},

showInterviewed: function () {
    this.collection.filterInterviewed();//returns a value you're not usingthis.render();
}

I suggest adding an optional parameter to your render method that represents the filtered collection. If the parameter is defined, use it. If not, use the unfiltered collection.

Borrowing some of @Simo's code to return a new collection.

filterActive: function () {
    var active = this.where({interviewed: false});
    return new ResumeCollection(active);
},

filterInterviewed: function () {
    var interviewed = this.where({interviewed: true});
    return new ResumeCollection(interviewed);
},

render: function (filtered) {
    var self = this;
    vardata = filtered ? filtered.toArray() : this.collection.toArray();
    this.$el.html( $('#filter') );
    _.each(data , function (cv) {
        self.$el.append((new ResumeView({model: cv})).render().$el);
    });
},

showActive: function () {
    var filtered = this.collection.filterActive();
    this.render(filtered);
},

showInterviewed: function () {
    var filtered = this.collection.filterInterviewed();
    this.render(filtered);
}

Solution 2:

Your issue is that you are not returning the filtered collection.

This should work:

filterActive: function () {
    var active = this.filter(function(item) {
        return item.get('interviewed') === false;
    });

    returnnewResumeCollection(active);
},

filterInterviewed: function () {
    var interviewed = this.filter(function(item) {
        return item.get('interviewed') === true;
    });

    returnnewResumeCollection(interviewed);
},

Solution 3:

i would suggest you to modify you render function to accept a argument which will be array of models.

Now when rendering full collection you can call render as

render(this.collection.models) // reference to list of models

also if you filter out the collection then the filter function most probably be returning the subset of models from collection. Which you can again pass to render function

this.render(this.showActive()) // showActive returns subset of models from collection

This way your render function becomes modular.. which accepts array and render then on page..

Now for Filtering out Collection you can use filter , where methods exposed by underscore .. Remember to capture the return and pass it along to render Function..

Post a Comment for "Filtering The Collection Doesn't Work"