Alex Rivera | Logout

jQuery: Unbind event handlers to bind them again later

Asked 2009-02-05T15:07:35.643
40

Does anybody know how to unbind set of event handlers, but memorize them in order to bind them again later? Any suggestions?

Edit
Report

1 Answer

8

Since jQuery 1.4.2+ changes how event handlers are stored, this seems relevant:

The best way I found was to use event namespacing:

var ary_handlers = [ fn_highlight, fn_onpress, fn_cleanup ];
for ( idx = 0; idx < ary_handlers.length; idx++ ){
  $('#test').bind('click.foobar',ary_handlers[idx]);
}

// and then later: 
$('#test').unbind('.foobar');  

In the above example, all foobar events unbound. Notice that if you needed finer grain control, you could namespace each click handler and correlate to your array of handlers:

var ary_handlers = [ fn_highlight, fn_onpress, fn_cleanup ];
for ( idx = 0; idx < ary_handlers.length; idx++ ){
  $('#test').bind('click.ns_' + String(idx), ary_handlers[idx]);
}

// and then later you could pick off a specific one to unbind
$('#test').unbind('.ns_2');
answered 2011-04-05T20:45:21.107

Your Answer