user1198485
user1198485

Reputation:

Show Collection Data in View In Backbone.js

I am new to backbone.js. I have 2 javascript files. 1 for collection and 1 for view.

**collection.js**

var colle = Backbone.Collection.extend({

    initialize: function () {
        var data = [
        { Name: "a", Image: "path1" },
        { Name: "b", Image: "path2" },
    ];
    }
});

and my view.js is

var View = Backbone.View.extend({

    initialize: function () {
        this.collection = colle;

    },

    render:function(){
            //How can I access that data here ?
    }

});


var view1 = new View();

How can I access my Collection data in View ?

Thank you.

Upvotes: 0

Views: 1230

Answers (1)

kinakuta
kinakuta

Reputation: 9037

First, you need an instance of your collection - currently you've defined colle as a constructor for a Backbone collection when what you need now is an instance:

var myCollection = new colle(); // convention is to use uppercase when defining your constructor

then, pass a reference to your collection when you instantiate your view:

var view1 = new View({ collection: myCollection });

then, inside your view you can reference your collection using this.collection:

render: function () {
    // reference your collection using this.collection here
}

If you can be more specific about what you want to do with your collection, I can expand the example to demonstrate something more useful.

Upvotes: 1

Related Questions