selanac82
selanac82

Reputation: 3000

Self initialize a backbone view

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.

Upvotes: 1

Views: 562

Answers (2)

nekman
nekman

Reputation: 1919

Just initialize the backbone view directly with the new operator:

var myView = new Backbone.View();

Or by using extend:

var myView = new (Backbone.View.extend({ 
      initialize : function() { console.log('init'); } 
}));

Upvotes: 1

mu is too short
mu is too short

Reputation: 434945

Backbone.View.extend() returns a constructor function so you can call new on it. The only tricky part is getting the precedence correct so that extend sees the arguments in its parentheses rather than new seeing them as arguments to the constructor:

var v = new (Backbone.View.extend({ ... }));

Demo: http://jsfiddle.net/ambiguous/TpmtH/

Without the extra set of parentheses:

var v = new Backbone.View.extend({ ... });

you'll be doing (more or less) this:

var V = Backbone.View.extend;
var v = new V({ ... });

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:

var myView = (function() {
    var BBview = Backbone.View.extend({});
    return new BBview();
})();

That may not be as pretty or clever but it has the enormous advantage of being a common and instantly recognizable pattern.

Upvotes: 4

Related Questions