简体   繁体   English

使用$ .proxy javascript调用函数

[英]calling a function using $.proxy javascript

I want to load a function on click event using $.proxy. 我想使用$ .proxy在click事件上加载函数。 If i load the function using the below click event then everything works fine. 如果我使用下面的click事件加载函数,则一切正常。

click event which is working 单击事件正在运行

$('element').click($.proxy(this.doProcess, this));

click event which is not working 点击事件不起作用

$('element').click(function(){
    // Perform other things
    $.proxy(this.doProcess, this);  
});

As you can see that i want to perform other things on the click event before loading the function. 如您所见,我想在加载函数之前对click事件执行其他操作。 Can you please help me figure out why it is not loading if i use ".click(function()..." instead of simply '.click()..' 如果我使用“ .click(function()...”而不是简单的“ .click()..”),您能帮我弄清楚为什么不加载吗?

Because in the first snippet the click function calls the returned function. 因为在第一个代码段中,click函数调用了返回的函数。 In the second snippet you are binding the current this value to the function, but you don't call the returned function. 在第二个代码段中,您将当前的this值绑定到函数,但没有调用返回的函数。 You can use the invocation operator ( () ) for calling the function: 您可以使用调用运算符( () )来调用该函数:

$.proxy(this.doProcess, this)();  

Note that this in the context of the anonymous function (which is the current event handler) doesn't refer to the this keyword's value of the outer context, you can cache the value: 请注意, this在匿名函数(这是当前的事件处理)的情况下不指this外上下文关键字的值,你可以缓存值:

var that = this;
$('element').click(function() {
    // Perform other things
    $.proxy(that.doProcess, this)(/* arguments go here */);  
//           |               |
//           |               ----- refers to the clicked element
//           ----- reference of the outer context's `this` value
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM