Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone collection.add is not working

I have a pretty basic setup like this:

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

The model is not actually added to the collection. If I try to use Chrome console and enter playlistCollection.length it will output 0 and playlistCollection.models will output [].

Any idea what I am doing wrong?

like image 673
ewooycom Avatar asked Dec 19 '12 10:12

ewooycom


1 Answers

Collections in Backbone already have an add method. By writing your own, you mask the base method and prevent the the normal behavior: inserting a model into the collection. Rename your method to something else or call the base method to solve your problem:

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/

like image 193
nikoshr Avatar answered Sep 19 '22 10:09

nikoshr