2015-05-10 57 views
0

我有一個骨幹和反應的混合。我試圖在changeSeasons方法中使用this(或那個,自己,無論)訪問骨幹視圖方法(在HomeView)。但是因爲在HomeMainComp組件中調用changeSeasons,所以this被綁定到反應組件。如何正確綁定this,以便我可以在我的changeSeasons方法中訪問Backbone視圖的方法?React.js,如何在組件外綁定`this`

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,但後來我需要this通過我changeSeasons方法與另一個結合?我有點困惑發生了什麼,在這種情況下,我不再可以訪問傳入變量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), 
+2

總是有'_.bindAll(這一點, 'changeSeasons')''中或initialize'也許'this.changeSeasons.bind(本)',而不僅僅是'this.changeSeasons'。雖然不知道什麼會對React最有意義。 –

回答

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') 
    ); 
    }, 

穆太短提到,下劃線提供了一個方便的功能,綁定一個或多個方法的對象:

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

我正朝着正確的方向前進,但我有點困惑發生了什麼事情。我用我的進步更新了我的問題。 – Ben

+0

@Ben'this.changeSeasons.bind(null,this)'不正確,你應該使用'this.changeSeasons.bind(this)'。然後參數問題消失。 –

+0

謝謝@BinaryMuse我以爲我這樣做了,它不起作用,一定是別的東西,我造成了一個問題。 – Ben