我可以使用嵌套的 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 来使代码工作。因为我在 myFunction 中需要 this
上下文,它是 jquery animate
api 的回调函数。
我可以这样使用吗?
最佳答案
它应该可以工作,但是我建议在外部作用域中存储对对象的引用将是一个更优雅的解决方案。注意本例中_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>
关于javascript - 我可以使用嵌套的 jquery.proxy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47416469/