32

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'});
Industrial
  • 41,400
  • 69
  • 194
  • 289
  • The accepted answer is INCORRECT. The answer from Brave Dave is correct (backbone has changed). Please downvote the accepted answer and upvote the one from Dave to show correct answer above, – Danubian Sailor Oct 18 '21 at 14:55

2 Answers2

58

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'});
czarchaic
  • 6,268
  • 29
  • 23
  • 11
    It should be noted that in this situation your newly created view will have `this.myVar` and `this.options.myVar`. If you're trying to overwrite `this.myVar` with options passed you may want to `this.myVar=this.options.myVar` in your initialize function. – czarchaic Dec 11 '11 at 11:43
  • 3
    Awesome! Quick find from Google. – Richard Clayton Mar 25 '12 at 14:17
  • Still Awesome quick & simple post in 2013 ! Thanks ^^ – Thomas Decaux Mar 21 '13 at 11:35
  • 2
    alternatively store `myVar` on an options object: `options: { myVar : 'Hello from inside' },`. The options will automatically be merged, and be available on `this.options` – Nico Burns Apr 09 '13 at 10:21
  • This answer, as for now, is INCORRECT. See the answer from Brave Dave to save yourself hurdle. – Danubian Sailor Oct 18 '21 at 14:56
28

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
});
Brave Dave
  • 1,300
  • 14
  • 9