35

The changelog to Backbone.js 1.1.0 states:

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

My question is how can I do it now? previously, I had this.var = this.options.var regularly in my views.

Joe
  • 1,841
  • 4
  • 27
  • 43
  • possible duplicate of [backbone.js: how to pass parameters to a view](http://stackoverflow.com/questions/7803138/backbone-js-how-to-pass-parameters-to-a-view) – mu is too short Jan 07 '14 at 02:24
  • 1
    I disagree. My question asked how to read the options within the view post-1.1.0 not how to pass the parameters to the view pre-1.1.0. – Joe Jan 07 '14 at 09:21

3 Answers3

69

If you want to access to passed options - just save them:

initialize: function (options) {
  this.options = options || {};
}

If you use ES6:

initialize (options = {}) {
  this.options = options;
}

If you want to save passed options for all Backbone.View's you can override constructor like ncksllvn suggested below.

Community
  • 1
  • 1
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
  • any reason not to include a typeof options !== 'undefined' check? – 1nfiniti Oct 28 '13 at 19:37
  • 1
    @mikeyUX, In any case `this.options` will be `undefined` :) – Vitalii Petrychuk Oct 28 '13 at 19:49
  • A couple other things to keep in mind if you take this route: 1) Views that don't have an initialize() defined need to add one like above, and 2) any direct calls to initialize (e.g. not using the `new` keyword) needs to pass the options as an argument. – Kyle Oct 29 '13 at 18:36
  • @Kyle I don't think you can pass `options` as an argument. Wouldn't it have to be within an `attributes` hash? And then if you did that, why not just name everything attributes instead of options? So far the above solution has not worked for me because of this.. – Trip Dec 06 '13 at 16:07
  • would it make sense to do this.options = arguments || {} and leave an empty argument? – Alexander Mills Jun 26 '15 at 01:24
34

My team was already invested in using this.options in certain instances, and I didn't want to go through and modify the initialize method for every subclass of Backbone.View. As soon as Backbone is loaded, we override the Backbone.View constructor similiar to McGarnagle's answer, but with seamless integration:

// Compatibility override - Backbone 1.1 got rid of the 'options' binding
// automatically to views in the constructor - we need to keep that.
Backbone.View = (function(View) {
   return View.extend({
        constructor: function(options) {
            this.options = options || {};
            View.apply(this, arguments);
        }
    });
})(Backbone.View);
ncksllvn
  • 5,699
  • 2
  • 21
  • 28
0

Also worth taking a look a backbone.viewOptions for a minimalist implementation of view options that supports white listing and default values.

Brave Dave
  • 1,300
  • 14
  • 9