Willem Ellis
Willem Ellis

Reputation: 5016

How do I pass properties to a Backbone view?

I was developing my app using Backbone v1.0.0 and between beginning work and now there has been an update to v1.1.0. So where I used to be able to do,

var myView = new MyView({hash: 'something'});

And access hash inside the view using,

this.options.hash

This no longer works. I now get the following error:

Uncaught TypeError: Cannot read property 'hash' of undefined

So what's the new way of doing this? I would very much like to be able to pass properties into my view.

Upvotes: 2

Views: 379

Answers (1)

mu is too short
mu is too short

Reputation: 434615

From the 1.1.0 ChangeLog:

  • Backbone Views no longer automatically attach options passed to the constructor as this.options, but you can do it yourself if you prefer.

So the constructor options are still passed to initialize but this.options is no longer automatically set up. You can do this:

initialize: function(options) {
    // Stash `options.hash` in `this` if you want or
    // `this.options = options;` if you want to emulate
    // the old behavior.
}

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

Upvotes: 7

Related Questions