views:

272

answers:

3

Hello,

I have the following code:

$('#form_field, #button').bind('change click', function() {
// take action
}

It works fine. However, I want to trigger the same action when 'change' is used for '#form_field' and 'click' for '#button' (not when 'click' is used for '#form_field').

I know that can be done using the following code:

$('#form_field').bind('change', function() {
// take action
}

$('#button').bind('click', function() {
// take action
}

However, I do not want to repeat all the code that is inside the function (// take action). It would look ineffective and I will need to edit it twice every time I make changes to it.

Any ideas?

Thanks in advance

+9  A: 

How about:

var myCoolFunction = function() {
  // take action
};
$('#form_field').bind('change', myCoolFunction);
$('#button').bind('click', myCoolFunction);

??

gnarf
Why don't u (and Nick Spiers in his answer) don't use `$('#button').click(myCoolFunction)` instead of `$('#button').bind('click',myCoolFunction)`? Same with `$('#button').bind('change',myCoolFunction)` and `$('#button').change(myCoolFunction)`. As I'm new to JQuery: Is there a specific reason? ~Chris
cimnine
Not really, it saves a whopping 1 function call.. inside of jQuery `$.fn.click = function(fn) { return fn ? this.bind('click', fn) : this.trigger('click'); };` ( although it isn't set directly that way, look @ line 3098 in jQuery-1.3.2.js )
gnarf
A: 

I'm not too sure it's that great an idea to find a way around this. If they both do the same thing, just make a function for them to call on the required events.

Jimmeh
+2  A: 

This should do the trick:

$('#form_field').bind('change', takeAction);

$('#button').bind('click', takeAction);

function takeAction () {
    //take action
};
Nick Spiers