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

1
  • You can namespace your event handlers and enable/disable groups of handlers that way. Commented Jun 22, 2012 at 7:52

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 If I can disable them and enable them without storing them that's very nice, I didn't even dare to hope this is possible.
@LajosArpad, I have added an example.
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/

1 Comment

This looks like a nice solution.
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.