admin管理员组文章数量:1414879
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?
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?
Share Improve this question edited Jan 29, 2012 at 13:10 PeeHaa 72.8k60 gold badges194 silver badges264 bronze badges asked Dec 24, 2010 at 4:27 Darryl HeinDarryl Hein 145k96 gold badges223 silver badges263 bronze badges2 Answers
Reset to default 6Neither..
$('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.
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);
本文标签: javascriptjQuery adding change event handler with predefined functionStack Overflow
版权声明:本文标题:javascript - jQuery: adding change event handler with predefined function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745203767a2647531.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论