javascript - jQuery: adding change event handler with predefined function - Stack Overflow

So I have the following:var change_handler = function(element) { ... do some fancy stuff ...}Now, I

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745203767a4616484.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信