When one event occurs, another will trigger, and by name. In some cases, the event handler of that event may call preventDefault . How to check if it was called and transfer this state to the first event?

https://jsfiddle.net/edgv8qur/1/

 $("button").click(function (event) { $("body").trigger("some-custom-event"); // Если кастомное событие было отменено, отменить и это if (true) { // Как проверить? event.preventDefault(); } }) $("body").on("some-custom-event", function (event) { if (Math.random() > .5) { console.log("prevent"); event.preventDefault(); } else { console.log("allow"); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>Test</button> 

PS: The same question in English.

2 answers 2

Found such a way, but something I do not like:

 $("button").click(function (event) { $("body") .one("some-custom-event", function (e) { if (e.isDefaultPrevented()) { event.preventDefault(); console.log("prevented!") } }) .trigger("some-custom-event"); }) $("body").on("some-custom-event", function (event) { if (Math.random() > .5) { console.log("prevent"); event.preventDefault(); } else { console.log("allow"); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>Test</button> 

    Based on the response from Mustafa Shujaie :

     $("button").click(function (event) { var e = $.Event("some-custom-event"); $("body").trigger(e); // Если кастомное событие было отменено, отменить и это if (e.isDefaultPrevented()) { event.preventDefault(); console.log("prevented!"); } }) $("body").on("some-custom-event", function (event) { if (Math.random() > .5) { console.log("prevent"); event.preventDefault(); } else { console.log("allow"); } }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>Test</button>