Backbone 1.1.0 Views - Reading Options

2019-01-22 05:53发布

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.

标签: backbone.js
3条回答
三岁会撩人
2楼-- · 2019-01-22 06:24

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

查看更多
不美不萌又怎样
3楼-- · 2019-01-22 06:34

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.

查看更多
Animai°情兽
4楼-- · 2019-01-22 06:35

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);
查看更多
登录 后发表回答