2

Say I have some actions binded to a link ( with .click or .live), and I want to do the same thing later, but I don't want duplicated code. Which is the correct way and why?

This:

$('#link').click(function(){
 //do stuff
});

//called later
$('#link').trigger('click');

OR:

$('#link').click(function(){
  do_stuff();
});

//called later
do_stuff();

//defined here
function do_stuff(){
   //do stuff
}
Nick Zinger
  • 1,174
  • 1
  • 12
  • 28

3 Answers3

2

Actually, you only need to distinguish between whether or not you're accessing the event object within the event handler. Another difference is that the context of that invoked handler might change, so this won't point to the invoked node when called directly.

If you're accessing this or the event object, you indeed should use .trigger to execute the handler. You could also pass in all necesarry data yourself by manually invoking the method, but why invent the wheel.

Otherwise, you're just fine in directly calling that function from wherever you have access to it.

jAndy
  • 231,737
  • 57
  • 305
  • 359
2

Note that context will differ in your code depending on the two actions.

In your anonymous callback function, this will refer to the link being clicked. In do_stuff it will not.

Other than that, I think it is often more semantically appealing to call a function that does what you want to do, than to simulate a click that has the side effect of triggering your listener. This is my personal preference, though.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • This answers my question thanks! (unfortunately, so does the other answer, basically saying the same thing, wish I could mark both as Accepted) – Nick Zinger Jul 17 '12 at 15:34
2

One problem with your first method is that you'll also trigger any other click events that get bound to that control; you can solve this with namespaces

$('#link').bind('click.mynamespace', function(){ ... });

$('#link').trigger('click.mynamespace');

or by using a second event

$('#link').bind('do_stuff', function(){ ... });
$('#link').click(function() { $(this).trigger('do_stuff'); });

However I'd go for the second one because it's simpler, provided you have closure access to the function where you need to call it. You don't need the extra function wrapper, BTW:

function do_stuff(event) { ... }
$('#link').click(do_stuff);
do_stuff();

If it is useful to define the function in a closure you no longer have access to, go for the first way.

Rup
  • 33,765
  • 9
  • 83
  • 112