la colección de la columna vertebral se devuelve como una matriz de objetos, pero no puede usar .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.

preguntado el 09 de marzo de 12 a las 16:03

1 Respuestas

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

respondido 09 mar '12, 16:03

thanks obmarg, I find I keep going back and forth on when I need to use the model,attributes and when not. - pedalear

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.