user1694873
user1694873

Reputation: 473

Iterate though Backbone.js collection

Im working my way through a backbone web app (pretty new to backbone) and need some help on iterating through a collection as I fetch it. What I want to do is loop over each element in the collection and if the progress attribute is 100 show an imported <div>, else show a loading <div>.

I have this working for the last element in the collection as follows:

fileRepositoryCollection.fetch({

    success: function () {

        if (fileRepositoryCollection.at(fileRepositoryCollection.length - 1).get('progress') === 100) {
            $('#loading').hide();
            $('#imported').show();
        } else {
            $('#loading').show();
            $('#imported').hide();
        }
    }
});

Upvotes: 0

Views: 520

Answers (1)

Rok Burgar
Rok Burgar

Reputation: 949

You shouldn't render html in a collection class. Your collection view should have a render method for rendering, defining how your collection looks in html. You then iterate trough the collection in a view.

Something like this:

var fileRepositoryCollectionView = Backbone.View.extend({

    render: function() {
        // collection rendering

        this.collection.each(function(file) {
           if (file.get('progress') === 100) {
                $('#loading' + file.get('some_id')).hide();
                $('#imported' + file.get('some_id')).show();
            } else {
                $('#loading' + file.get('some_id')).show();
                $('#imported' + file.get('some_id')).hide();
            }
        });

        return this;
    },
});

var repView = new fileRepositoryCollectionView({ collection: fileRepositoryCollection});

Upvotes: 1

Related Questions