Industrial
Industrial

Reputation: 42758

Backbone.js - passing arguments through constructors

Scenario:
I got an alert() saying undefined when I (try to) set the myVar variable through the Constructor. However if I uncomment the myVar that's living inside the myView, the alert then instead says "Hello from inside", just as one would expect.

Question:
Does this mean that I cannot set any params in the constructor of the view except backbones own params, such as model, collection, el, id, className & tagName?
Manual: http://documentcloud.github.com/backbone/#View-constructor

The code:

var myView = Backbone.View.extend({

    //myVar : 'Hello from inside',

    initialize: function() {
        alert(this.myVar);
    }
)};

new myView({myVar: 'Hello from outside'});

Upvotes: 32

Views: 17546

Answers (2)

Brave Dave
Brave Dave

Reputation: 1300

As of backbone 1.1.0, the options argument is no longer attached automatically to the view (see issue 2458 for discussion). You now need to attach the options of each view manually:

MyView = Backbone.View.extend({
    initialize: function(options) {
        _.extend(this, _.pick(options, "myVar", ...));
        // options.myVar is now at this.myVar
    }
});

new MyView({
    myVar: "Hello from outside"
    ...
});

Alternatively you can use this mini plugin to auto-attach white-listed options, like so:

MyView = BaseView.extend({
    options : ["myVar", ...] // options.myVar will be copied to this.myVar on initialize
});

Upvotes: 28

czarchaic
czarchaic

Reputation: 6318

Options passed into the constructor are automatically stored as this.options

var myView = Backbone.View.extend({

  myVar : 'Hello from inside',

  initialize: function() {
      alert(this.options.myVar);
  }
)};

new myView({myVar: 'Hello from outside'});

Upvotes: 58

Related Questions