React.js,如何在组件外绑定`this`

时间:2015-05-10 22:04:05

标签: backbone.js reactjs

我有骨干和反应的混合物。我正在尝试使用this(或那个,self,无论如何)来访问HomeView方法中的主干视图方法(changeSeasons)。但是因为在changeSeasons组件中调用了HomeMainComp,所以this绑定到react组件。如何正确绑定this以便我可以在changeSeasons方法中访问Backbone视图的方法?

HomeView = Backbone.View.extend({

  initialize: function(){
      // init stuff
      this.fetchData();
  },

  fetchData: function(){
      // fetch stuff then runs renderReact...
  },

  renderReact: function(){
    React.render(
      <HomeMainComp
        changeSeasons={this.changeSeasons}
        probablePitchers={this.probablePitchers.toJSON()} />,
        document.getElementById('app')
      );
  },

  changeSeasons: function(seasons){
      console.log(this); // shows the HomeMainComp...,
      this.pitcherStats.setSeasons(seasons); // so this don't work
      this.fetchData(); // this don't work either
  },

    ...

})
编辑:通过下面的一些建议,我可以将HomeView作为我的this,通过绑定(null,this)到changeSeasons,但是我需要在我的changeSeasons中传递this方法与另一个绑定?我有点困惑发生了什么,在这种情况下,我再也无法访问传入的变量seasons

  renderReact: function(){

    React.render(
      <HomeMainComp
        changeSeasons={this.changeSeasons.bind(null, this)}
        probablePitchers={this.probablePitchers.toJSON()} />,
        document.getElementById('app')
            );
     },

  changeSeasons: function(_this){
    console.log('this: ', _this) ## this gives me the HomeView object
    console.log('Season change: ', seasons); ## but now I'm having trouble accessing my incoming seasons variable, which is empty because _this is taking the space.
      _this.pitcherStats.setSeasons(seasons);
      _this.fetchData();
  }.bind(this),

1 个答案:

答案 0 :(得分:2)

渲染组件时可以绑定changeSeasons

  renderReact: function(){
    React.render(
      <HomeMainComp
        changeSeasons={this.changeSeasons.bind(this)}
        probablePitchers={this.probablePitchers.toJSON()} />,
        document.getElementById('app')
      );
  },

每次调用renderReact时都会创建一个新函数。虽然可能不是什么大问题,但如果你想最小化函数创建/ GC,你可以更早地绑定它:

  initialize: function(){
      // init stuff
      this.changeSeasons = this.changeSeasons.bind(this);
      this.fetchData();
  },

  // ...

  renderReact: function(){
    React.render(
      <HomeMainComp
        changeSeasons={this.changeSeasons}
        probablePitchers={this.probablePitchers.toJSON()} />,
        document.getElementById('app')
      );
  },

由于mu太短,Underscore提供了一个方便的功能来将一个或多个方法绑定到一个对象:

  initialize: function(){
      // init stuff
      _.bindAll(this, "changeSeasons");
      this.fetchData();
  },