0

This question has been asked several times, but none of the solutions offered are working for me.

In this Backbone collection, how can I access and loop through its models?

I've tried several ways in the code below; includes additions based on Mark V.'s answer.

Code is also available here: http://jsfiddle.net/LPbsP/3/

(function() {

console.log(Backbone);

window.App = {
    Model: {},
    Collection: {},
    View: {}
};

App.Model.Whatever = Backbone.Model.extend({});

App.Collection.Whatever = Backbone.Collection.extend({
    model: App.Model.Whatever,

    initialize: function(models, options) {
        this.getModels();

        _.bindAll(this, 'getModelsWithBindAll');
        this.getModelsWithBindAll();

        console.log(this);
        console.log(models);
        models.each(function(model) {
            console.log(model);
        });
    },

    getModels: function() {
        console.log('in getModels');
        console.log(this);

        whateverCollection.each(function(model) {
            console.log(model);
            console.log(model.toJSON());
        });
    },

    getModelsWithBindAll: function() {
        console.log('in getModelsWithBindAll');
        console.log(this);

        whateverCollection.each(function(model) {
            console.log(model);
            console.log(model.toJSON());
        });
    }
});

var whateverCollection = new App.Collection.Whatever([
    {
        name: 'jim',
        title: 'boss'
    },
    {
        name: 'tom',
        title: 'worker'
    }
]);

console.log('program code');
console.log(whateverCollection);

})();

Results:

Object (Backbone)

in getModels

r (length: 0, models: Array[0] ... )

Cannot call method 'each' of undefined

Here are the other questions I referenced:

Community
  • 1
  • 1
cantera
  • 24,479
  • 25
  • 95
  • 138

1 Answers1

2

There are two ways.

  1. If you need to iterate over them in the initialize method, then declare your initialize method as initalize(models, options) as that is how Backbone will call it. Then iterate over the models parameter as you would over a regular array. This is because this.models has not been filled with models at the time initialize is called.

  2. If you don't need to iterate in the initialize method, then after you define your whateverCollection, just do:

     whateverCollection.each(function(model) {    
       console.log(model);    
       console.log(model.toJSON());    
     })    
    
Mark Vayngrib
  • 974
  • 5
  • 14
  • Thanks for responding - could you take a look at this fiddle: http://jsfiddle.net/LPbsP/2/? I'm still unable to get initialize() to wait for the collection to be passed in. – cantera Sep 18 '13 at 13:47
  • I updated the question to include the fiddle code, so you can just reference above - thanks again – cantera Sep 18 '13 at 13:57