bricker
bricker

Reputation: 8941

Can't iterate through Collection in Backbone.js

Update

It was a stupid typo. I was using Backbone.Model.extend for the collection. facepalm


Trying to iterate through a collection but I think I've populated it incorrectly or something:

RecentContent = Backbone.View.extend
    initialize: ->
        @collection = new ContentAPI.ContentCollection()

        @collection.fetch
            success: (collection, response, options) =>
                console.log @collection
                # d {attributes: Object, _escapedAttributes: Object, cid: "c4", changed: Object, _silent: Object…}
                # property `attributes` contains Objects from server

                console.log @collection.models # undefined
                @render()

    #---------------------

    render: ->
        # ERROR: Object has no method 'each'
        @collection.each (model) ->
          console.log model

I also noticed that if I tried to bind the reset event to @collection (instead of render from within the success callback), it never seems to get fired.

The collection is very simple:

class ContentAPI
    @Content: Backbone.Model.extend {}

    @ContentCollection: Backbone.Model.extend
        url: "/api/content/"
        model: @Content

I'm a little new to Backbone so thank you for helping. :)

Upvotes: 0

Views: 1221

Answers (2)

TYRONEMICHAEL
TYRONEMICHAEL

Reputation: 4244

I am no coffeescript expert, but I think your problem is

@ContentCollection: Backbone.Model.extend

It should be

@ContentCollection: Backbone.Collection.extend

Also when iterating over your collection's models, use

_.each(collection.models, function(model) { console.log(model); });

Upvotes: 1

loganfsmyth
loganfsmyth

Reputation: 161457

The problem is that your collection is inheriting from the wrong base class.

@ContentCollection: Backbone.Model.extend

should be

@ContentCollection: Backbone.Collection.extend

Upvotes: 1

Related Questions