Collections 主干集合作为对象数组返回,但可以';每个都不用

Collections 主干集合作为对象数组返回,但可以';每个都不用,collections,backbone.js,models,each,Collections,Backbone.js,Models,Each,我觉得我以前遇到过这个问题,但这与其他时候不同 我有一个事件集合,需要对它们进行迭代 我建立我的收藏 MyApp.Collections.UserEvents = Backbone.Collections.extend({ model: MyApp.Models.Event, url: 'user_events/' + User.id, initialize: function() { } }); MyApp.Models.Event = Backbone.Mo

我觉得我以前遇到过这个问题,但这与其他时候不同

我有一个事件集合,需要对它们进行迭代

我建立我的收藏

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

MyApp.Models.Event = Backbone.Model.extend({});
我在路由器中获取集合,然后获取视图

MyApp.userEvents = new MyApp.Collections.UserEvents();
MyApp.userEvents.fetch({
    success: function() {
        MyApp.UserEvents.trigger(new MyApp.Views.UserEvents);
    }
});
在视图中,我尝试遍历事件

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)
    }
});
在我的控制台里

[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'

所以从我的角度来看,我得到了一个事件数组,但由于某些原因,我无法通过迭代得到每个事件

问题是您正在调用
MyApp.userEvents.models
上的each函数,它是一个原始javascript数组,因此没有each函数。您应该对集合本身调用each函数,如下所示:

MyApp.userEvents.each( this.add );
或者,如果确实要使用数组而不是集合对象,可以直接使用下划线.js:

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

问题是您正在调用
MyApp.userEvents.models
上的each函数,它是一个原始javascript数组,因此没有each函数。您应该对集合本身调用each函数,如下所示:

MyApp.userEvents.each( this.add );
或者,如果确实要使用数组而不是集合对象,可以直接使用下划线.js:

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

感谢obmarg,我发现当我需要使用
模型
属性
和不需要时,我会不断重复。感谢obmarg,我发现当我需要使用
模型
属性
和不需要时,我会不断重复。