javascriptbackbone.jsbackbone-events

When initializing a backbone view


How do I make it so that a function runs every time a backbone.js view is initialized?

I'm looking for something that I can put on outside of my normal view code, as an extension to backbone.js.

The idea is to reduce the amount of boilerplate.


Solution

  • Since Javascript is not a true object oriented programing language, you can't use inheritance to solve your problem as you could if it was java or c#.

    One possible solution is to use the factory design pattern.

    Instead of instantiating your view directly, you can call a factory method that will instantiate your view.

    var viewFactory = function(view, viewOptions) {
      //perform your boilerplate code
      return new view(viewOptions);
    }
    
    AView = Backbone.View.extend({});
    
    var person = new Backbone.Model({name: 'Paul'});
    var view = viewFactory(AView, { model: person });
    

    Here's a jsfiddle example

    It's not as an elegant solution that is possible with other languages, but it does the job.