jQuery: adding change event handler with predefined function

╄→尐↘猪︶ㄣ 提交于 2019-12-07 18:37:47

问题


So I have the following:

var change_handler = function(element) {
    // ... do some fancy stuff ...
}

Now, I want to attach this to an element. Which is the better/best or more correct method?

$('element_selector').change(change_handler(this));

Or...

$('element_selector').change(function() { change_handler(this); });

And does it make any difference if you're passing the object to the function or not?


回答1:


Neither..

$('element_selector').change(change_handler);

change_handler will be the so to speak pointer to the method and the argument of the element is already passed by jQuery

If you were to use $('element_selector').change(change_handler(this)); it wouldn't actually assign the method as the handler but rather run the method and attempt to assign the result as the handler, the other option is superfluous because you can use the method name as described above instead of re-wrapping the method.




回答2:


This is another way to approach the problem given by the OP... partial function application a la another SO Q. Bind the change handler with the arg of interest and pass the resulting partial as the arg to the change handler:

var myChangeHandler = partial(change_handler, this);
$('element_selector').change(myChangeHandler);


来源:https://stackoverflow.com/questions/4524207/jquery-adding-change-event-handler-with-predefined-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!