3

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?

ProblemsOfSumit
  • 19,543
  • 9
  • 50
  • 61
  • 1
    This seems related to one of my favorite js questions: [Use of 'prototype' vs. 'this' in JavaScript?](http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript) – mrak May 02 '15 at 12:25
  • @mrak wtf I feel like an idiot now. Thanks for sharing this question! Definitely opened my eyes on the issue. – ProblemsOfSumit May 02 '15 at 12:41

1 Answers1

2

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
Ram
  • 143,282
  • 16
  • 168
  • 197
  • worksl ike a charm! So properties and their values of backbone views are shared accross instances? Thank you for explaining this to me! – ProblemsOfSumit May 02 '15 at 12:29