Question

I am in need of extending the major Backbone functions (View, Model, Router) with some own members. However, the following does not work properly:

Backbone.View.prototype.foo = ["bar"];

Admittedly, the expression

testView = new Backbone.view.extend({})
testView2 = new Backbone.view.extend({})
alert(testView.foo.length);

states 1 but setting

testView2.foo.push("blah");

also added the string to testView.foo since the reference is identical.

Anyone has a smart idea how to extend those objectsm anyway?

Thanks in advance :)

Leo

Was it helpful?

Solution

Normally you would not extend the standard View, and instead would create your own base view type. You should avoid changing values on the Backbone prototypes.

var BaseView = Backbone.View.extend({
  foo: null,
  initialize: function(options){
    this.foo = ["bar"];

    Backbone.View.prototype.initialize.apply(this, arguments);
  }
});

var testView = new BaseView();
var testView2 = new BaseView();
console.log(testView.foo.length); // prints '1'
console.log(testView2.foo.length); // prints '1'    

testView2.foo.push("blah");

console.log(testView.foo.length); // prints '1'
console.log(testView2.foo.length); // prints '2'    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top