For Loop over Backbone Collection

前端 未结 3 804
耶瑟儿~
耶瑟儿~ 2021-01-17 13:06

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 i

相关标签:
3条回答
  • 2021-01-17 13:23

    You want to loop over the models property of the collection, not the collection object itself.

    0 讨论(0)
  • 2021-01-17 13:27
    for object in object.models
    

    This will give you a model in the collection

    0 讨论(0)
  • 2021-01-17 13:33

    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.

    0 讨论(0)
提交回复
热议问题