Backbone 1.1.0 Views - Reading Options

2019-01-22 06:16发布

问题:

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.

回答1:

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.



回答2:

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);


回答3:

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



标签: backbone.js