views:

288

answers:

5

I have a function that is bound for a page object in some Javascript files that are loaded on each page.

I need to add some more functionality to that already defined event handler. Here is an example of what i mean.

The object with the currently defined click event closes a pop-up div that appears on the screen. When this is clicked (only on this certain page), i need it to reset some elements on the page.

So, i can easily enough unbind the click event, and rebind a custom one, but it would be copying a lot of code from the original close event.

If worse comes to worse, i can just do that, but i would like to avoid copying that code for this special case.

Is there a way to, sort of, append more code on to a currently created event?

thanks for any insight!

A: 

Set up the click event as function e.g.

$(element).click(function(){//do stuff in here});

You can add what you want in the function bit call more functions or whatever.

matpol
@matpol I think I edited the wrong one. Mea culpa
Elzo Valugi
+1  A: 

just bind another handler with the added functionality

just somebody
A: 

You can use event delegation. google the term for some tutorials

Basically works by binding the event to a parent imutable element and then deciding the actions by the childrens that are clicked. This way you can add/remove children type x without having to bind/rebind actions to it.

$("#parent_global_div").click( function (ev) {
   var el = $(ev.target);
   if( el === x){
       //do something
   }

});

Elzo Valugi
A: 

You could use "bind" and then the click method could call "trigger" on all of these bound events.

bobwah
A: 

Events are queued on jquery, so all assigned/bind events gets called. If for a specific reason you need to bind/unbind only that particular queued event, namespaced that event.

$('button').click(function(){alert(1);});
$('button').click(function(){alert(2);});
//The 2 function gets called when the button is clicked 

$('button').unbind('click');//all handlers are removed.


//Namespaced event
$('button').click(function(){alert(1);});
$('button').bind('click.custom',function(){alert(2);});
//The 2 function gets called when the button is clicked 


$('button').unbind('click.custom');//only the click.custom is unbind
jerjer