code_junkie

jQuery: Unbind event handlers to bind them again later

Nov 14th, 2011
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. $(document).ready(function() {
  2. $('#test').click(function(e) {
  3. alert('test');
  4. var events = $('#test').data("events");
  5. $('#test').unbind('click', events.click[0]);
  6. });
  7. });
  8.  
  9. <a id="test">test</a>
  10.  
  11. var ary_handlers = [ fn_highlight, fn_onpress, fn_cleanup ];
  12. for ( idx = 0; idx < ary_handlers.length; idx++ ){
  13. $('#test').bind('click.foobar',ary_handlers[idx]);
  14. }
  15.  
  16. // and then later:
  17. $('#test').unbind('.foobar');
  18.  
  19. var ary_handlers = [ fn_highlight, fn_onpress, fn_cleanup ];
  20. for ( idx = 0; idx < ary_handlers.length; idx++ ){
  21. $('#test').bind('click.ns_' + String(idx), ary_handlers[idx]);
  22. }
  23.  
  24. // and then later you could pick off a specific one to unbind
  25. $('#test').unbind('.ns_2');
  26.  
  27. (function($){
  28.  
  29. function obj_copy(obj){
  30. var out = {};
  31. for (i in obj) {
  32. if (typeof obj[i] == 'object') {
  33. out[i] = this.copy(obj[i]);
  34. }
  35. else
  36. out[i] = obj[i];
  37. }
  38. return out;
  39. }
  40.  
  41.  
  42. $.fn.extend({
  43.  
  44. storeEvents:function(){
  45. this.each(function(){
  46. $.data(this,'storedEvents',obj_copy($(this).data('events')));
  47. });
  48. return this;
  49. },
  50.  
  51. restoreEvents:function(){
  52. this.each(function(){
  53. var events = $.data(this,'storedEvents');
  54. if (events){
  55. $(this).unbind();
  56. for (var type in events){
  57. for (var handler in events[type]){
  58. $.event.add(
  59. this,
  60. type,
  61. events[type][handler],
  62. events[type][handler].data);
  63. }
  64. }
  65. }
  66. });
  67. return this;
  68. }
  69.  
  70. });
  71. })(jQuery);
Add Comment
Please, Sign In to add comment