Answer the question
In order to leave comments, you need to log in
How to check for an array entry?
Hello, I'm trying to experiment with backbone js.
I wanted to make a simple collection filter
var mClub = new Cafe([
{id: 1, name: "name 1", kitchens: [1,2], show: 1},
{id: 2, name: "name 2", kitchens: [1,3], show: 1},
{id: 3, name: "name 3", kitchens: [2], show: 1},
{id: 4, name: "name 4", kitchens: [1], show: 1},
{id: 5, name: "name 5", kitchens: [3], show: 1},
]);
var filters = new Filter([
{id: 1, kitchens: new Array()}
]);
var Cafe = Backbone.Collection.extend({
model: CafeModel,
check : function(filter) {
var show = true;
var a = filter.get('kitchens');
this.filter(function(cafe) {
var b = cafe.get('kitchens');
// Попытка с indexOf - не работает
// если задать а и b ручками - то работает
// var a = [1,3]; var b = [3,2]
for (var i = 0; i < b.length; i++){
if(_.indexOf(a, b[i])){
//alert('есть вхождение')
}
}
//через фильтр - работает
b.filter(function(c){
for (var i = 0; i < a.length; i++){
if( a[i] == c){
//alert('есть вхождение')
}
}
});
});
}
});
Answer the question
In order to leave comments, you need to log in
I would do like this:
var filter = new Filter();
filter.add([
{id: 1, kitchens: new Array()},
{id: 2, kitchens: [2]},
{id: 3, kitchens: [2, 3]},
{id: 4, kitchens: []}
])
Filter = Backbone.Collection.extend({
initialize : function() {
this.on('add', this.check);
},
check : function(model) {
model.set('show', model.get('kitchens').length ? 1 : 0);
}
});
Another interesting moment is how to make a chain of filters, now I have driven all the checks into one check function
All this can be underscored (as backbone prequels), either through a filter or an include. For chain .chain().… .value()
http://stackoverflow.com/questions/11762105/filter-backbone-collection-by-attribute-value interesting method
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question