Search code examples
collectionsbackbone.jsmodelseach

backbone collection being returned as array of objects, but can't use .each


I feel like I've been in this problem before, but this is different than other times.

I have a collection of events and need to iterate over them .

I build my collection

MyApp.Collections.UserEvents = Backbone.Collections.extend({
    model: MyApp.Models.Event,
    url: 'user_events/' + User.id,
    initialize: function() {
    }
});

MyApp.Models.Event = Backbone.Model.extend({});

I fetch the collection in my router, and then get the view

MyApp.userEvents = new MyApp.Collections.UserEvents();
MyApp.userEvents.fetch({
    success: function() {
        MyApp.UserEvents.trigger(new MyApp.Views.UserEvents);
    }
});

in the view I try to iterate through the events

MyApp.Views.UserEvents = Backbone.Views.extend({
    el: 'div#user_events',
    initialize: function() {
        user_events = MyApp.userEvents.models;
        console.log(user_events);
        this.render();
    },
    render: function() {
        user_events.each(this.add);
    },
    add: function(event) {
        console.log(event)
    }
});

in my console I get

[d, d, d, d, d, d, d, d, d, d, d, d, d, d]

UserEvents.js:16Uncaught TypeError: Object [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] has no method 'each'

So the way I'm seeing it, I've got an array of the events, but for some reason I can't get each one of the events by iterating over them.


Solution

  • The problem is that you're calling the each function on MyApp.userEvents.models which is a raw javascript array, and therefore does not have an each function. You should call the each function on the collection itself, like so:

    MyApp.userEvents.each( this.add );
    

    Or if you really want to use the array rather than the collection object, you could use Underscore.js directly:

    _.each( user_events, this.add, this );