Jquery - run click and function call?

Let's say I have some actions bound to a link (with .click or .live) and I want to do the same later, but I don't want to duplicate the code. What is the right way and why?

It:

$('#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 } 
+2
source share
3 answers

In fact, you only need to distinguish whether you are accessing an event object in an event handler. Another difference is that the context of this handler may change, so this will not refer to the called node when called directly.

If you are accessing this or event object , you really need to use .trigger to execute the handler. You can also transfer all the necessary data manually using the method, but why reinvent the wheel.

Otherwise, you can simply call this function directly from anywhere you have access to it.

+2
source

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

In your anonymous callback function, this will refer to the link you click. In do_stuff this will not be.

In addition, I think that it is often more semantically attracted to calling a function that does what you want to do than to simulate a click, which has the side effect of starting your listener. This is my personal preference.

+2
source

One of the problems with your first method is that you also trigger any other click events that are bound to this control; you can solve this with namespaces

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

or using the second event

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

However, I would go for the second one, because it is easier if you have access to a function where you need to call it. You do not need an additional functional shell, BTW:

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

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

+2
source

All Articles