I’m wondering if there is a simple way to self initialize a backbone view. It’s probably best I show an example of what I’m looking to do.
Currently the default way to initialize a backbone view is as follows:
var BBview = Backbone.View.extend({});
var myView = new BBview();
For name-spacing reasons I’d like to “auto” or “self” initialize the backbone view. For example.
var MyApp.MyView = Backbone.View.extend({}).initialize();
This way MyApp.MyView will automatically become my view instead of having to first create a variable to be the backbone view and then also create another variable to initialize it. Hopefully this makes sense. Any help is much appreciated. Thanks guys.
Backbone.View.extend()returns a constructor function so you can callnewon it. The only tricky part is getting the precedence correct so thatextendsees the arguments in its parentheses rather thannewseeing them as arguments to the constructor:Demo: http://jsfiddle.net/ambiguous/TpmtH/
Without the extra set of parentheses:
you’ll be doing (more or less) this:
and that’s not what you want.
I wouldn’t recommend this sort of thing, you’ll just confuse and puzzle whoever ends up looking at your code in six months. You’re better off using a function to avoid namespace pollution:
That may not be as pretty or clever but it has the enormous advantage of being a common and instantly recognizable pattern.