jquery .on itself

后端 未结 3 1162
闹比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条回答
  •  猫巷女王i
    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.

提交回复
热议问题