0
votes

I'm using Backbone.js purely on the front-end side to leverage some of of its really nice features, but it's giving me hard time.

I get my JSON array inside the data-json attribute on one div:

<div class="json-data" data-json = "[{ img: "aaa", price: "Bla Bla"... }]">

I load it like this:

//CoffeeScript
@baseCollection = new ComparisonCollection $(@el).find(".json-data").data("json") 

Collection is created correctly. It has 43 models as expected. After creating it I want to filter out models using this regex /Unknown/.test(model.get("price")) to filter out items with the price starting with "Unknown"

That code looks like this:

@baseCollection.each (obj)-> 
  if /Unknown/.test(obj.get("price"))
    obj.collection.remove(obj)
, @

In my collection I have 10 objects/models with price == "Unknown" or "Unknown " and only 5 of them get removed! The regex is correct and the loop enters the IF block 10 times...

I guess there's something wrong with my understanding of the remove() method...

1
I guess, in this case, collection length will changed after removing model from collection. I suggest you copy your collection and remove from it. in the end set the collection to original collection. Or you use filter function - Ulug'bek Ro'zimboyev
Thanks! length changes after I call remove(), but that's expected behaviour. Right? I believe that _.filter might be what I'M looking for! Thanks! - luigi7up

1 Answers

0
votes

http://underscorejs.org/#filter and http://backbonejs.org/#Collection-set

obj.collection.set(obj.collection.filter(function(o){
    return /Unknown/.test(o.get('price'));
}));

Where the reg test will have to test for models to kee pin the collection and set will perform a smart remove/add. Plus, as Ulugbek said, you wont be modifying your view while still iterating through it

Sorry that i dont know coffeescript!