2012-02-29 3 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を使用する予定がある場合は、関数の定義で太い矢印=>を使用してバインドを避けることができます。同じことをしますか? – Radek

答えて

5

これは私がやる方法です。 bindAllの素晴らしい点の1つは、LocationFormViewに追加機能を追加すると、自動的にthisがバインドされるということです。

+0

_.bindAll(これ); - 私が必要とするものすべて。 Tnks! – RredCat

+0

あなたはバインドする必要のある関数に渡す必要があります。この場合、 '_.bindAll(これ、 'onSuccessUpdatePos'、 'onFailUpdatePos')' –

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); 

、すなわち。

関連する問題