2013-03-31 41 views
3

我有一个骨干的集合,获取一些数据,但是当我尝试使用各种方法在集合迭代它得到骨干收集不有没有这样的方法各有

Object [object Array] has no method 'each' 

下面是收集的模型:

define (['backbone'],function(Backbone){ 
    return Backbone.Model.extend({ 
     url:'http://some_url/api/post/', 
    }); 
});//end define 

集合本身: '

define (['backbone','models/Post'],function(Backbone,Post){ 
return Backbone.Collection.extend ({ 
    model: Post, 

    initialize: function (model) 
    { 
     this.userId = model.userId; 
     this.start = model.start; 
    }, 

    url: function() 
    { 
     return "http://some_url.com/api/post?userid=" + this.userId + "&start=" + this.start; 
    }, 

    parse: function (response) 
    { 
     return response; 
    } 

    }); 
    }); 

这是实例使用集合视图中的呼叫:

cookieVal = document.cookie.split ("; "); 
       posts = new PostCol ({userId:id = cookieVal[0].split('=')[1],start:1}); 

       posts.fetch().success (function (response){ 
        post = new Post({collection:response}); 
        post.render(); 
        console.log (post.el); 
       }); 

和视图的实现,它使用的收集:

define (['jquery','underscore','backbone','views/Actor'],function($,_,Backbone,Actor){ 
return Backbone.View.extend ({ 
    className:'moment mb30', 

    render: function() 
    { 
     console.log (this.collection); 
     this.collection.each (function (model){ 
      actor = new Actor ({model:model}); 
      this.$el.append (actor.render().el); 
     },this); 
     return this; 
    } 
}); 
}); 

为什么不工作的每个方法和哪能解决这个问题。

+1

行'console.log(this.collection);'print?你把'this.collection'分配给了一个'Backone.Collection'吗? – Howard

+0

它打印[对象,对象,对象,对象] – user2054833

回答

1

下面是一个更习惯的方式来做到这一点,也可以修复你的错误,虽然你的代码有点奇怪,但我没有看到它的具体错误。

posts = new PostCol({userId:id = cookieVal[0].split('=')[1],start:1}); 
post = new Post({collection:posts}); 
posts.on('reset', post.render.bind(post)); //This should really go in PostView initialize 
posts.fetch(); 
+0

这行代码是做什么的? post.render.bind(post) – user2054833

+1

它确保当调用'reset'触发和'render'时,它被绑定到'this'的视图实例调用。 –

-1

有没有这样的方法each()。你的意思是forEach()?您需要在您的Backbone页面中包含underscore.js以使用迭代功能。

+1

是的,骨干集合直接实现所有的下划线方法。 http://documentcloud.github.com/backbone/docs/backbone.html#section-115 –

+0

@PeterLyons哦对,所以应该有'each'方法? – Jivings