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
}
4

3 に答える 3

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.

于 2012-07-17T09:01:46.560 に答える
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.

于 2012-07-17T09:01:54.487 に答える
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.

于 2012-07-17T09:03:09.240 に答える