JSFiddle - React, Tailwind, and code Playground

by David Kyle

HTML

<div id="wrapper">
    <input type="button" name="button1" id="button1" value="Delayed events" />
    <input type="button" name="button2" id="button2" value="Nested events" />
</div>

JavaScript

$(function () {
    var shouldCancel = false;
    //First event
    //Without the setTimeout, this event would be triggered first.
    $("#button1").click(function (e) {
        setTimeout(function () {
            if (!shouldCancel) {
                alert("test2");
            } // end if
        }, 500);
    });
    //Second event
    $("#button1").click(function (e) {
        alert("test1");
        shouldCancel = true;
        e.stopPropagation();
        e.preventDefault();
    });

    $("#button2").click(function (e) {
        // ..some operation that makes some check and assigns a value to the "shouldCancel" property below
        $(document).trigger("should-continue", {
            shouldBeCanceled: shouldCancel,
            callback: function () {
                alert("test2");
            }
        });

    });

    $(document).bind("should-continue", function (e, data) {
        if (data.shouldBeCanceled) {
            e.stopPropagation();
            e.preventDefault();
            return;
        } else {
            alert("test1");
            data.callback(); // Call the method specified by the caller
        } // end if/else
    });
});