For 循环主干集合 [英] For Loop over Backbone Collection

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

问题描述

对主干相当陌生,所以这是一个非常基本的问题.我有一个 Backbone 集合传递给一个函数,我可以证明它已经被传递并且集合中的模型有 id.

这是我设置 ID 的方式 -

convertToMapObjects: (results) =>objectList = new ObjectList()结果.每个(结果)->testObj = new TestObject()测试对象集id = result.get("id")objectList.add(testObj)

在另一个函数中(通过使模型触发事件访问)-

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

我认为这个问题可能是因为我是如何遍历集合的,因为当我尝试这样做时

for object in objects控制台日志(对象)

我看到了两个 undefined.这个对吗?如果是这样,为什么我不能使用 for 循环来遍历主干集合?另外,有没有办法做到这一点?

解决方案

Backbone 集合不是数组,因此 for ... in 不会产生您期望的结果.如果您想使用简单的循环,您需要查看集合的 models 属性.>

然而,Backbone 集合有混合各种下划线方法:

<块引用>

下划线方法 (28)

Underscore.js 的 Backbone 代理,在 Backbone.Collection 上提供 28 个迭代函数.它们并未全部记录在此处,但您可以查看 Underscore 文档以获取完整详细信息......

  • forEach(每个)
  • ...

所以你可以使用 mappluck 如果您想避免访问 模型 属性:

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

pluck 方法或多或少只是 map 的一个特例,但集合实现了原生版本而不是使用 Underscore 版本,以便它们可以 pluck 模型属性而不是简单的对象属性.

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)

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:

Underscore Methods (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 (each)
  • ...

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.

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

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