0

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.

1 Answers1

1

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.

kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • But How Can I Access "data" variable inside initialize function ? –  May 16 '13 at 05:06
  • @Rajeev: Normally you'd pass that data to the collection constructor call: `new colle([ { Name: "a", Image: "path1" }, ... ])` or get it from the server with a `fetch` call. – mu is too short May 16 '13 at 05:53