BackboneJS overview: View.extend ()
Until today, I thought that with basic functions like
var PageView = Backbone.View.extend({
template: $.Deferred,
getTemplate: function(tplName) {
var self = this;
ajaxCall(tplName).then(function(hbs) {
self.template.resolve(hbs);
});
}
});
var home = new PageView();
home.getTemplate('home.hbs');
is similar to pure JS OOP approach such as
var PageView = function() {
this.template = $.Deferred();
}
PageView.prototype.getTemplate = function(tplName) {
var self = this;
ajaxCall(tplName).then(function(hbs) {
self.template.resolve(hbs);
});
}
var home = new PageView();
home.getTemplate('home.hbs');
However, I am currently trying to rebuild a web application using a trunk and it looks like the solution is deferred since
home.getTemplate('home.hbs');
will allow this for all instances of the Backbone view PageView
, whereas in pure JS this would only allow for one specific instance home
.
When I make a second instance:
var page1 = new PageView();
the property is template
already resolved with a template home.hbs
in the backbone. This is very strange to me.
So my guess is that I fundamentally misunderstand how pivot points work. Can someone enlighten me?
source to share
The difference is in the first template
property attribute of all instances referring to the same object, and in the second snippet the property is set using a different / new instance of the Deferred constructor function. If you set the property template
in a initialize
constructor function , you get the same result as the second snippet:
var PageView = Backbone.View.extend({
// template: $.Deferred,
initialize: function() {
this.template = $.Deferred;
},
getTemplate: function(tplName) {
var self = this;
ajaxCall(tplName).then(function(hbs) {
self.template.resolve(hbs);
});
}
});
In the second example, if you set template
in a prototype
constructor, then it will behave like a pipeline constructor:
var PageView = function() {
// this.template = $.Deferred();
}
PageView.prototype.template = $.Deferred();
var instance1 = new PageView();
var instance2 = new PageView();
console.log( instance1.template === instance2.template ); // true
source to share