Backbone.js - passing arguments through constructors

后端 未结 2 731
野趣味
野趣味 2021-02-01 15:54

Scenario:
I got an alert() saying undefined when I (try to) set the myVar variable through the Constructor. However i

相关标签:
2条回答
  • 2021-02-01 16:19

    Options passed into the constructor are automatically stored as this.options

    var myView = Backbone.View.extend({
    
      myVar : 'Hello from inside',
    
      initialize: function() {
          alert(this.options.myVar);
      }
    )};
    
    new myView({myVar: 'Hello from outside'});
    
    0 讨论(0)
  • 2021-02-01 16:29

    As of backbone 1.1.0, the options argument is no longer attached automatically to the view (see issue 2458 for discussion). You now need to attach the options of each view manually:

    MyView = Backbone.View.extend({
        initialize: function(options) {
            _.extend(this, _.pick(options, "myVar", ...));
            // options.myVar is now at this.myVar
        }
    });
    
    new MyView({
        myVar: "Hello from outside"
        ...
    });
    

    Alternatively you can use this mini plugin to auto-attach white-listed options, like so:

    MyView = BaseView.extend({
        options : ["myVar", ...] // options.myVar will be copied to this.myVar on initialize
    });
    
    0 讨论(0)
提交回复
热议问题