简体   繁体   English

For Loop over Backbone Collection

[英]For Loop over Backbone Collection

Fairly new to backbone, so this is a really basic question. 骨干相当新,所以这是一个非常基本的问题。 I have a Backbone collection passed into a function and I can prove that it has been passed and that the models in the collection have ids. 我有一个Backbone集合传递给一个函数,我可以证明它已经通过,并且集合中的模型有id。

Here's how I'm setting the ids - 这是我如何设置ID -

convertToMapObjects: (results)  =>
   objectList = new ObjectList()
   results.each(result)->
    testObj = new TestObject()
    testObj.set
      id = result.get("id")
    objectList.add(testObj)

And in another function ( accessed through making the model trigger an event) - 在另一个函数中(通过使模型触发事件来访问) -

getIds: (objects) =>
ids = (object.id for object in objects) 

I think the issue may be because of how I'm iterating through the collection because when I tried doing 我认为问题可能是因为我正在迭代这个集合,因为当我尝试的时候

for object in objects
   console.log(object)

I saw two undefineds. 我看到两个未定义的。 Is this correct? 它是否正确? If so, why can't I use a for loop to go through a backbone collection? 如果是这样,为什么我不能使用for循环来通过骨干集合? Also, is there a way I could do so? 还有,我有办法吗?

A Backbone collection is not an array so for ... in won't produce the results you're expecting. Backbone集合不是一个数组,所以for ... in将不会产生你期望的结果。 You want to look at the collection's models property if you want to use a simple loop. 如果要使用简单循环,则需要查看集合的models属性。

However, Backbone collections have various Underscore methods mixed in : 但是,Backbone集合中混合了各种Underscore方法

Underscore Methods (28) 下划线方法(28)

Backbone proxies to Underscore.js to provide 28 iteration functions on Backbone.Collection . Backbone代理Underscore.js,在Backbone.Collection上提供28个迭代函数。 They aren't all documented here, but you can take a look at the Underscore documentation for the full details… 它们并未全部记录在案,但您可以查看Underscore文档以获取完整的详细信息......

  • forEach (each) forEach(每个)
  • ... ...

So you can use map or pluck if you'd like to avoid accessing the models property : 因此,如果您想避免访问models属性,可以使用mappluck

ids = objects.map (m) -> m.id
ids = objects.pluck 'id'

The pluck method is, more or less, just a special case of map but collections implement a native version rather than using the Underscore version so that they can pluck model attributes rather than simple object properties. pluck方法或多或少只是map一个特例,但集合实现了本机版本而不是使用Underscore版本,因此它们可以采用模型属性而不是简单的对象属性。

您希望遍历集合的models属性 ,而不是集合对象本身。

for object in object.models

这将为您提供集合中的模型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM