views:

202

answers:

3
    ==dom is like this==

   <a href='javascript:void(0)' id='link1'>elm with  events bound initially</a>
   <a href='javascript:void(0)' id='link2'>elm to which events are bound in future</a>

    ====js==
    $(function(){
    $('#link1').bind('click',function(){alert('do something to make me happy');})
    });

    //now some time in future i want to copy all events bound on link1 to link2

//iam doing it as written below
// please suggest some better way if possible or available


        var _elmEvents = $(#link1).data('events');

        if (_elmEvents) {
           $.each(_elmEvents, function (event, handlers) {
             $.each(handlers, function (j, handler) {
                 $('#link2').bind(event, handler);
             });
           });
        }
+2  A: 

Check out this resource.

Gavin Gilmour
Hmm, good to know. Sorta wish i woulda seen this comment before I essentially wrote this plugin in mine. :)
BBonifield
+1  A: 

You can clone an element and manipulate the new element however you want, however jQuery doesn't provide an easy way to copy event handlers from one element to another. However, the code that would do it would be:

var events = jQuery.data( originalElement, "events" );

for ( var type in events ) {
    for ( var handler in events[ type ] ) {
        jQuery.event.add( targetElement, type, events[ type ][ handler ], events[ type ][ handler ].data );
    }
}

But since it relies somewhat on jQuery internals, I would try to make a solution using clone.

noah
+2  A: 

If you want to copy all events from one object to another without cloning, you can do so by accessing the events data directly.

For instance, if you did:

$("#the_link").click(function(e){
    // do some stuff
    return false;
}.mouseover(function(e){
    // do some other stuff
});

You can access those event associates in the 'events' data of the element

var events = $("#the_link").data('events');

It will be an object whose keys represent the event type, each containing an array of event associations. EX: http://bobbonifield.com/grab/4faabb.png .Regardless, here's a simple example, not accounting for namespaces.

var events = $("#the_link").data('events');
var $other_link = $("#other_link");
if ( events ) {
    for ( var eventType in events ) {
        for ( var idx in events[eventType] ) {
            // this will essentially do $other_link.click( fn ) for each bound event
            $other_link[ eventType ]( events[eventType][idx].handler );
        }
    }
}
BBonifield