Alex Rivera | Logout

How to make Backbone.js Collection items Unique?

Asked 2011-06-20T20:17:58.133
16

Say I have these Backbone.js Model:

var Truck = Backbone.Model.extend({});

var truck1 = new Truck();
var truck2 = new Truck();

truck1.set("brand", "Ford");
truck2.set("brand", "Toyota");
truck3.set("brand", "Honda");
truck4.set("brand", "Ford");

Then, let's say we have a Backbone.js Collection:

var TruckList = Backbone.Collection.extend({
  model: Truck,
  comparator: function(truck) {
     return truck.get("brand");
  };

});

I'm a car collector, so time to add each car to my collection:

Trucks = new TruckList();
Trucks.add(truck1);
Trucks.add(truck2);
Trucks.add(truck3);
Trucks.add(truck4);

Just focusing on the brand attribute, truck4 is a duplicate of truck1. I can't have duplicates in my Collection. I need my collection to have unique values.

My question is, How do I remove duplicate items from my Backbone.js Collection?

Should I use Underscore.js for this? If so, can someone please provide a working/runnable example of how to do this.

Assume the following:

1.Collection is not sorted

  1. Removal must be done on brand attribute value

  2. Ajax call to populate each instance of a Truck. This means when adding to a collection, you don't have access to the Truck properties.

Edit
Report

1 Answer

1

Not sure if this is an update to either Backbone or underscore, but the where() function works in Backbone 0.9.2 to do the matching for you:

TruckList.prototype.add = function(truck) {
    var matches = this.where({name: truck.get('brand')});

    if (matches.length > 0) {
        //Up to you either return false or throw an exception or silently ignore
        return false;
    }

    Backbone.Collection.prototype.add.call(this, truck);
}
answered 2012-06-06T20:06:22.063

Your Answer