简体   繁体   中英

How can I tell if an event is being fired by the same event that created it?

Let's say I have the following events:

$(button).on('mouseup', function (event1) {
    $(something).show();

    $(document).on('mouseup', function (event2) {
        $(something).hide();
    });

});

So, it shows "something" when button is clicked and hides it when the document is clicked. How can I make sure the second evnet doesn't trigger in the same event that created it? right now the something will show and hide instantly (at least on firefox).

I need to do this without any globals of any kind, preferably.

How about this:

$(button).on('mouseup', function (event1) {
    $(something).show();
    event1.stopPropagation();
    $(document).one('mouseup', function (event2) {
        $(something).hide();
    });

});

stopPropagation() will stop the event from going past the button (to the document).

one() will only run the event once and then go away... can be recreated again with another click on the button.

JSFiddle

Here's another solution that doesn't rely on timestamps:

$("button").on('mouseup', function (event1) {
    $("#something").show();

    setTimeout(function () {
        $(document).one('mouseup', function (event2) {
             $("#something").hide();
        });
    }, 0);

}); 

demo

Using setTimeout with a delay of 0 will make it execute the code as soon as it's finished with this event. Also note I'm using one rather than on because you only need this event handler one time and without it you will end up attaching unlimited numbers of event handlers, every single one of which will need processing when a mouseup fires anywhere on your page.

A less silly solution might look like this:

$("button").on('mouseup', function (event1) {
     $("#something").show();
});

$(document).on('mouseup', function (event2) {
    if(event2.target != $("button")[0]) {
        $("#something").hide();
    }
});

demo

Why don't you isolate the event like so:

$(button).on('mouseup', function (event1) {
    $(something).show();
});

$(document).on('mouseup', function (event2) {
        $(something).hide();
});

I ended up using the event.timeStamp property to check if the two events are distinct. Also added an unbind and a namespace to the document event to prevent event stacking.

$(button).on('mouseup', function (event1) {
    $(something).show();

    $(document).on('mouseup.'+someIdentifier, function (event2) {
        if(event1.timeStamp != event2.timeStamp) {
            $(something).hide();
            $(document).unbind('mouseup.'+someIdentifier);
        }
    });

});

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