3

Ok, let's say that I have a button and I would like to enable/disable its click handlers.

I would like to create functions like these:

var bar = [];
function storeHandlers(buttonID) {
    //I would like to store the click handlers in bar[buttonID]
}

function preventHandlers(buttonID) {
    storeHandlers(buttonID);
    //I would like to disable all the click handlers for button
}

function loadHandlers(buttonID) {
    //I would like to enable all the handlers loaded from bar[buttonID]
}

Is this possible? How can I achieve this?

Thank you in advance

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175

3 Answers3

2

As far as I know you can't store/retrieve the event handlers from just the ID of the elements, you have store those manually while creating handlers. But you can on/off handlers like following

function preventHandlers(buttonID) {
    $('#'+buttonID).off('click',bar[buttonID]);
}

function loadHandlers(buttonID) {
   $('#'+buttonID).on('click',bar[buttonID]);
}

And you can store them like

bar[buttonID] = function(event){

};

UPDATE:

Though the answers here at How to debug JavaScript/jQuery event bindings with Firebug (or similar tool) and here How to find event listeners on a DOM node when debugging or from the JavaScript code? and others are saying that .date('events') returns all event handlers, i could not get it to work.

I have set up an example with the way stated above. Chek the following link

Working Fiddle

Community
  • 1
  • 1
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
1

Just try this:

function preventClick(buttonID) {
    $('#'+buttonID).data('events').saved_click = $('#'+buttonID).data('events').click;
    $('#'+buttonID).data('events').click = null;
}

function allowClick(buttonID) {
    $('#'+buttonID).data('events').click = $('#'+buttonID).data('events').saved_click;
}

That's it!

jsFiddle example: http://jsfiddle.net/cec6z/9/

Baris Akar
  • 4,895
  • 1
  • 26
  • 54
0

Maybe I'm wrong but I don't think you can retrieve all event callbacks from a jquery object such like

var handlers = $('#buttonId').unbind('click')
Christoph
  • 50,121
  • 21
  • 99
  • 128