ProblemsOfSumit
ProblemsOfSumit

Reputation: 21325

Understanding backboneJS: View.extend()

Until today I thought using backbones functionality 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 a pure JS OOP approach like

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'm currently trying to rebuild a web-app with backbone and it seems like solving that deferred with

home.getTemplate('home.hbs');

will resolve this for all instances of the Backbone view PageView while in pure JS this would only resolve for that one particular instance home.

When I do a second instance:

var page1 = new PageView();

the template property is already resolved with the home.hbs template in backbone. Which is very weird to me.

So my guess is that I'm fundamentally misunderstanding how backbone views work. Can someone enlighten me?

Upvotes: 3

Views: 269

Answers (1)

Ram
Ram

Reputation: 144689

The difference is in the first snippet template property of all the instances refer to the same object and in the second snippet the property is set using a different/new instance of Deferred when the constructor function is executed. If you set the template property within the initialize function of the constructor you will 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 the template to the prototype of the constructor then it will behave like the backbone 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

Upvotes: 2

Related Questions