Lucas Michaels
Lucas Michaels

Reputation: 11

Overriding Backbone Collection Add Error

I have the following Backbone Collection. My problem is when I do car.get("brand"), I get undefined.

The brand attribute is there. I know because when I do console.log(car), I can see it. It's as if the .get property doesn't exist on the car object. But that is impossible because I place my Car Model script, before my Cars Collection script.

So isDupe is failing as a result. Not even sure if this.any is being called. But 100% .get is not there! Help!

var Cars = Backbone.Collection.extend({
model: Car,
add: function(object) {
        var car = new Car(object);

        var isDupe = false;

        isDupe = this.any(function(_car) { 
            return _car.get("brand") === car.get("brand");
        });

        console.log("isDupe: " + isDupe);

        if (isDupe) {
            return false;
        }

        Backbone.Collection.prototype.add.call(this, car);
    }
}

Upvotes: 1

Views: 2354

Answers (1)

Bill Eisenhauer
Bill Eisenhauer

Reputation: 6183

My version of this would look something similar to this:

Car = Backbone.Model.extend({

  eql: function(other) {
    return this.get('brand') == other.get('brand');
  }

});

CarList = Backbone.Collection.extend({

  model: Car,

  add: function(newCar) {
     isDupe = this.any(function(car) {
       return car.eql(newCar);
     });
     if (isDupe) return;
     Backbone.Collection.prototype.add.call(this, newCar);
  }

});

Upvotes: 5

Related Questions