jquery .on itself

后端 未结 3 1161
闹比i
闹比i 2021-01-21 12:55

I want an element to listen for a custom event that is actually triggered by itself. The custom event could possibly be triggered from a descendant but should then be ignored. I

相关标签:
3条回答
  • 2021-01-21 13:40

    .on works fine; to ignore ancestors check e.target:

    $el.on('customEvent', function(e) {
      if(e.target === this) {
        //Do whatever
      }
    });
    
    0 讨论(0)
  • 2021-01-21 13:54

    The selector that you can pass to .on() is used for the delegate target to match elements that can handle the click event (and it should be a string, not an object).

    But in your case that's not necessary because your selector and the delegate target is the same thing, so this should work as expected:

    $el.on('customEvent', function(evt) {
        //Do whatever
    });
    

    To detect if an event came from a descendent you would compare evt.target against the element itself.

    0 讨论(0)
  • 2021-01-21 13:56

    Removing the part that doesn't work, will make it work.

    $el = $('#dialogDiv');
    $el.on('customEvent', function(e) {
        //Do whatever
    });
    $el.dialog({
        open: function() {
            $el.trigger('customEvent');
        }
    });
    

    However, you are asking for other features that a normal event might not support. You should look into setting up a jQuery special event. Check this awesome article by Ben Alman.

    When it comes to your prerequisites:

    • An event is always able to bubble unless its propagation is hindered with event.stopPropagation() or event.stopImmediatePropagation()
    • The trigger and the listener is already on the same element
    • The listener will not know what triggered it unless you pass some an argument that can identify the element that triggered it and check if it's an ancestor

    See test case on jsFiddle.

    0 讨论(0)
提交回复
热议问题