2
votes

I want to define a parent view in Backbone which extends Backbone.View. All child views will inherit from the parent view. But everytime I make a new instance of a child view, I want a function in the parent view to execute. Here's an example (the fiddle is here):

    SimpleSample = {};

    SimpleSample.ParentView = Backbone.View.extend({

        initialize: function(){
            //always execute this
            console.log('in parent view initialise');
        }
    });

    SimpleSample.Child1 = SimpleSample.ParentView.extend({

        initialize: function(){
            console.log('in child 1 initialise');
        }
    });


    SimpleSample.Child2 = SimpleSample.ParentView.extend({

    });

    SimpleSample.App = function(){
        this.start = function(){
            var child1 = new SimpleSample.Child1();
            var child2 = new SimpleSample.Child2();
        }
    }

    $(function(){
        var app = new SimpleSample.App();
        app.start();
    })

The output of this is, as you would expect:

in child 1 initialise
in parent view initialise

Because I have defined initialize() for Child1, the code in initialize() defined in ParentView does not run. I do not want to have to explicitly call a ParentView function from each child. Is it possible to always execute some code in ParentView every time there is a new instance of a view which inherits from ParentView?

3

3 Answers

2
votes

We've been using the Backbone-Super plugin for over a year. Well-tested & easy to add to most projects. With it the sub-class's initialize would look something like this:

initialize: function(options) {
    console.log('in child 1 initialise');
    this._super(options);
}

It never calls the super-class "automatically", but it does make it easy enough to make the call correctly. It works with all methods too, not just initialize, so ...

set: function(attributes, options) {
     this._super(attributes, options);
     console.log('Child 1 just had "set" called');
}
1
votes

You could override the constructor (in the parent view)

SimpleSample.ParentView = Backbone.View.extend({

   initialize: function(options){
       //always execute this
       console.log('in parent view initialise');
   }

   constructor: function (options) {
       Backbone.View.apply(this, arguments);
       SimpleSample.ParentView.prototype.initialize.apply(this, options);
   }

});

That takes care of calling the original constructor function from Backbone.View and also calls your initialize function.

Now your child views should be free to define their own initialize functions.

0
votes

There is no real super in javascript.

You could call a function in the parent view explicit via the prototype object

SimpleSample.Child1 = SimpleSample.ParentView.extend({

    initialize: function(){
        console.log('in child 1 initialise');
        SimpleSample.ParentView.prototype.initialize.apply(this);
    }
});

http://jsfiddle.net/yzowyhc5/5/