简体   繁体   中英

Make sure jQuery delegate handler is only attached once

I have a function that attaches a jQuery delegate handler onto the click event of an element:

function foo() {
      $(document).delegate("#fooElement", "click, function(event) {

      });
}

The foo function could get called multiple times throughout the life of the page and the handler could at times be removed. What is the best way to ensure that at most only once instance of this handler is attached at a time? Should I do something like this to remove the handler then re-attach it:

function foo() {
      $(document).undelegate().delegate("#fooElement", "click, function(event) {

      });
}

Or do I need to keep track of a boolean isHandlerAttached . Ideally, there would be an even cleaner way to do this, but I haven't found any in the jQuery documentation.

document is quite a generic element everyone is adding events to so i would suggest name spacing the event name. Also delegate & undelegate is deprecated and you should use on/off instead

$(document).off('click.foo', '#fooElement').on('click.foo', '#fooElement', function(e) {
    // put your logic in here
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM