覆盖Backbone Collection添加错误

时间:2011-06-23 01:57:18

标签: javascript backbone.js underscore.js

我有以下Backbone Collection。 我的问题是当我做car.get(“品牌”)时,我得到了不确定。

品牌属性就在那里。我知道,因为当我做console.log(汽车)时,我可以看到它。就好像汽车对象上不存在.get属性一样。但这是不可能的,因为我在我的汽车收集剧本之前放置了我的汽车模型脚本。

所以isDupe因此失败了。甚至不确定是否正在调用。 但是100%。不存在!帮助!

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);
    }
}

1 个答案:

答案 0 :(得分:5)

我的版本看起来与此类似:

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);
  }

});
相关问题