2012-02-29 58 views
2

我是backbonejs的新手。我正在嘗試將正確的this對象傳遞給回調函數,其中該函數是該視圖的一種方法。有沒有更好的方法將「this」對象傳遞給回調函數?

我目前的解決方案:

APP.LocationFormView = APP.View.extend({ 
    initialize: function() {  
     if (navigator.geolocation) { 
      var that = this; 

      var success = function(position) { 
       _.bind(that.onSuccessUpdatePos, that, position)(); 
      }; 

      var error = function(error) { 
       _.bind(that.onFailUpdatePos, that, error)(); 
      } 

      navigator.geolocation.getCurrentPosition(success, 
                error); 
     } else { 

     } 
    }, 

    onSuccessUpdatePos: function(position) { 
     // We can access "this" now 
    }, 

    onFailUpdatePos : function(error) { 
     // We can access "this" now 
    } 
}); 

這是一個正確的方式來實現我想要什麼? 有沒有更少的詳細解決方案呢?

+0

如果您打算使用CoffeeScript,而不是在函數定義中使用fat arrows =>來使用bind。做同樣的事情。 – Radek 2012-03-01 11:56:12

回答

5

這就是我該怎麼做的。 bindAll的一個很好的方面是,如果您將其他功能添加到LocationFormView,它們將自動綁定this

APP.LocationFormView = APP.View.extend({ 
    initialize: function() { 
     _.bindAll(this); 
     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(this.onSuccessUpdatePos, 
                this.onFailUpdatePos); 
     } else { 

     } 
    }, 

    onSuccessUpdatePos: function(position) { 
     // We can access "this" now 
    }, 

    onFailUpdatePos : function(error) { 
     // We can access "this" now 
    } 
}); 
+0

_.bindAll(this); - 所有我需要的。 TNKS! – RredCat 2012-11-10 11:50:16

+0

你必須通過它需要綁定的功能。在這種情況下:'_.bindAll(this,'onSuccessUpdatePos','onFailUpdatePos')' – 2016-07-02 07:15:09

2

_.bind用於以後的綁定。你通常會做的是這樣的:

that.onSuccessUpdatePos(position); // that is already the context 

但是相反,你可以通過它直接:

var success = _.bind(that.onSuccessUpdatePos, that, position); 
var error = _.bind(that.onFailUpdatePos, that, error); 

navigator.geolocation.getCurrentPosition(success, error); 

也就是說,如果感覺比「手動」解決方案更清楚你。

相關問題