Backbone collection.add无效

时间:2012-12-19 10:07:12

标签: javascript backbone.js underscore.js

我有一个非常基本的设置:

var MusicModel = Backbone.Model.extend({});
var PlaylistCollection = Backbone.Collection.extend({
    model: MusicModel,
    events: {'add':'add'},
    add: function(mdl){
        //This is working perfectly fine even output of model
        console.log(mdl);
    }
});

var playlistCollection = new PlaylistCollection();
playlistCollection.add(new Music(data));

模型实际上并未添加到集合中。如果我尝试使用Chrome控制台并输入playlistCollection.length,则输出0,playlistCollection.models将输出[]

知道我做错了吗?

1 个答案:

答案 0 :(得分:7)

Backbone中的集合已经有add method。通过编写自己的方法,可以屏蔽基本方法并阻止正常行为:将模型插入集合中。将您的方法重命名为其他方法或调用基本方法来解决您的问题:

var PlaylistCollection = Backbone.Collection.extend({
    model: MusicModel,

    add: function(model, opts){
        Backbone.Collection.prototype.add.call(this, model, opts);
        console.log(model);
    }
});

http://jsfiddle.net/nikoshr/WPrTu/