1

quick and probably dumb question. I have the following situation: I select multiple elements and bind a click handler to them. After they are clicked I want to remove the handler and unbind the click from all of them. $(this) always refers to the element that is actually clicked, so $(this) only removes the click handler from the element that is clicked - not from all selectors I bind the event to.

$(modal + ' .modal-close, ' + modal + ' a.cancel_link, ' + modal + ' .okBtn').bind('click', function(e) {
        e.preventDefault();
        ...
        //$(this).unbind('click');
        $(modal + ' .modal-close, ' + modal + ' a.cancel_link, ' + modal + ' .okBtn').unbind('click');
});

The weird question is. Is there a better way to this or do I have to repeat all selectors within the function to unbind the click from all selectors? I know I could declare a variable before, but is there anything like $(this-all) :)

2 Answers 2

1

You can capture the initial jQuery object in the closure:

var $all = $(modal + ' .modal-close, ' + modal + ' a.cancel_link, '
    + modal + ' .okBtn');
$all.click(function(e) {
    e.preventDefault();
    // ...
    $all.unbind("click");
});
1

Declaring a variable, as you said, is probably your best bet.

$(this-all) would not make sense in a lot of situations, because the click event doesn't know the particular selector you used when you bound that event, it just knows the element and the function to execute.

Note that there is a neater way of doing what you're doing. Rather than building a selector piece by piece, you can use the .find() method to find ancestors of the selected element:

var $modal = $(modal); // assuming `modal` is a string
var $elems = $modal.find('.modal-close, a.cancel_link, .okBtn'); // hyphens, underscores, and camelCase -- oh my!
$elems.click(...);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.