Search code examples
javascriptbackbone.js

Always execute parent function in Backbone


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?


Solution

  • 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.