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 impossi开发者_StackOverflow社区ble 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);
}
}
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);
}
});
精彩评论