对于遍历集合骨干 [英] For Loop over Backbone Collection

查看:137
本文介绍了对于遍历集合骨干的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相当新的支柱,所以这是一个非常基本的问题。我有一个骨干收集传递给函数,我可以证明它已经过去了,而且集合中的车型有标识。

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.

下面就是我如何设置的标识 -

Here's how I'm setting the ids -

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)

我看到了两个undefineds。它是否正确?如果是这样,为什么我不能用一个for循环都要经过骨干集合?此外,有没有一种方法,我可以这样做?

I saw two undefineds. Is this correct? If so, why can't I use a for loop to go through a backbone collection? 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. You want to look at the collection's models property if you want to use a simple loop.

不过,主干收藏有各种下划线方法混合:

However, Backbone collections have various Underscore methods mixed in:

下划线方法(28)

骨干代理来Underscore.js提供关于 Backbone.Collection 28迭代功能。他们是不是都记录在这里,但你可以看看下划线文档中的全部细节...

Backbone proxies to Underscore.js to provide 28 iteration functions on Backbone.Collection. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…


      
  • 的forEach(每个)

  •   
  • ...

  •   

所以,你可以使用 地图 或的 勇气 如果你想避免访问的 模式属性

So you can use map or pluck if you'd like to avoid accessing the models property:

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.

这篇关于对于遍历集合骨干的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆