2017-11-21 7 views
1

入れ子になったjquery.proxyを使うことはできますか?入れ子になったjquery.proxyを使うことができます

var obj = { 
    init: function(element){ 
     element.on('click.mynamespace',$.proxy(function (event) { 
      $(event.currentTarget).animate({ 
      scrollLeft: scrollPos 
      }, width, $.proxy(this.myFunction,this)); 
     },this)) 
    }, 
    myFunction: function(){ 
     /*some code*/ 
    } 
} 

これは私のプロジェクトに必要なものです。私は入れ子になった$ .proxyを使ってコードを動作させました。なぜなら、jquery animate apiのコールバック関数であるmyFunctionにthisというコンテキストが必要だからです。 このように使用できますか?

答えて

1

これはうまくいくはずですが、外側のスコープにオブジェクトへの参照を格納する方がより洗練されたソリューションになると思います。この例では_objの定義と使用に注意してください:

var scrollPos = 10; 
 
var width = 20; 
 
var obj = { 
 
    init: function($element) { 
 
    var _obj = this; 
 
    
 
    $element.on('click.mynamespace', function(e) { 
 
     $(this).animate({ 
 
     scrollLeft: scrollPos 
 
     }, width, _obj.myFunction.call(this)); 
 
    }); 
 
    }, 
 
    myFunction: function() { 
 
    // this function now executes within the context of the 
 
    // element which has been animated in the click handler 
 
    console.log(this.id); 
 
    } 
 
} 
 

 
var $foo = $('#foo'); 
 
obj.init($foo); 
 
$foo.trigger('click.mynamespace');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="foo"></div>

関連する問題