Answer the question
In order to leave comments, you need to log in
How to solve backbone collection filtering problem?
I decided that it was time to grow up and relearn how to code jquery - I chose backbone to start with, in order to more or less deal with client-side MVC.
The view is redrawn, the models are saved, but the collections are not filtered:
there is a collection with a filter (everything is simple):
var AdList = Backbone.Collection.extend({
url: "/ads",
model: app.Ad,
byParam: function (param) {
param = param || {};
var filtered = this.filter(function (ad) {
var byDevice = param.device ? _.contains(_.pluck(ad.get('devices'), 'title'), param.device) : 1,
byPlatform = param.platform ? _.contains(_.pluck(ad.get('platforms'), 'title'), param.platform) : 1;
var byOldVersions = 1, byLastVersion = 1;
if(param.for_old_versions){
byOldVersions = ad.get('for_old_versions');
}
if(param.for_last_version){
byLastVersion = ad.get('for_last_version');
}
return byDevice && byPlatform && byOldVersions && byLastVersion;
});
// console.log('filtered', new AdList(filtered));
return (filtered);
},
});
app.Ads = new AdList([{"id":91,"title":"asldknnsadl"}, ....]); // тут json с сервера
this.on('filter', function(param){
this.collection.reset(this.collection.filtering(param));
}, this);
Answer the question
In order to leave comments, you need to log in
reset - resets the entire collection and adds new models specified by you to it, i.e. judging by your code, you filtered the models and added them to the collection, models that do not satisfy the filter will drop.
That is, if you want to reset rerendering, then you need a new collection, or you can write a method in the view that will draw your collection for the specified filters:
this.on('filter', function(attr,val){
$('collectionContainer').empty();
_.each(this.collection.search(attr,val),this.addOne,this);
}
search: function(attribute,value) {
var val = _.trim(value);
if( val === '' ) {
return this.models;
}
return this.filter(function(x){
var regForCompany = new RegExp(val, "i");
return x.get(attribute).match(regForCompany);
});
},
In order to filter models in a collection, there are standard backbone functions this.collection.where({}) and this.collection.findWhere({}). Basically, they should be enough for you. Read more here
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question