Backbone.js - How is the View finding this Collection?
-
25-10-2019 - |
Question
I'm going through a tutorial to learn how to use Backbone.js and I'm having a hard time understanding how Backbone views are "seeing" the collection.
Below is the View code, and underneath that is the Collection code.
I can see that the variable $albums is being assigned to the particular class '.albums' that is within the element, but I don't get how this code is referencing 'this.collection'.
Both the view and the collection are being extended from standard Backbone.View and Backbone.Collection classes. Just from looking at it, I can't see how they even know each other exist. I'm assuming that the word 'this' refers to this particular instance of LibraryView.
I guess this is my primary question:
How is it that the code collection = this.collection
is able to see the external collection?
// A wrapper view to display each album in Library
window.LibraryView = Backbone.View.extend({
tagName: 'section',
className: 'library',
initialize: function() {
_.bindAll(this, 'render');
this.template = _.template($('#library-template').html());
this.collection.bind('reset', this.render);
},
render: function() {
var $albums,
collection = this.collection;
$(this.el).html(this.template({}));
$albums = this.$('.albums');
collection.each(function(album) {
var view = new LibraryAlbumView({
model: album,
collection: collection
});
$albums.append(view.render().el);
});
return this;
}
});
Here is the Albums collection:
// Albums Collection
window.Albums = Backbone.Collection.extend({
model: Album,
url: '/albums'
})
EDIT:
I think I found it thanks to the help here:
There was another piece of code creating a library variable and assigning it to a new albums collection:
window.library = new Albums();
Also, in the Router there is an initialize statement that passes in the 'library' variable:
initialize: function() {
this.libraryView = new LibraryView({
collection: window.library
});
Now it seems to make more sense. :)
Just posting this in case someone else is as confused as I was.
Solution
A collection would have to be passed to the LibraryView constructor. For example,
myLibrary = new LibraryView({
collection: new Albums()
})
However, an important bit of magic happens here. Everything passed to a View constructor ends up in the View's options
property. A select number of properties though, get copied over on to the view itself. So you can say this.collection
instead of this.options.collection
.
Those special properties are:
'model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'