Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone 1.1.0 Views - Reading Options

Tags:

backbone.js

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.

like image 236
Joe Avatar asked Oct 11 '13 18:10

Joe


2 Answers

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.

like image 96
Vitalii Petrychuk Avatar answered Nov 10 '22 20:11

Vitalii Petrychuk


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);
like image 33
ncksllvn Avatar answered Nov 10 '22 20:11

ncksllvn