Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass preventDefault call to other event?

When the event occurs, some other event is triggered by its name. In some cases the second handler can call preventDefault. How to pass this call to original event?

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

$("button").click(function (event) {
  $("body").trigger("some-custom-event");

  // If the custom event was prevented, prevent original one too
  if (true) { // How to check?
    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: Same question in Russian.

like image 753
Qwertiy Avatar asked Jan 17 '26 22:01

Qwertiy


1 Answers

You can pass an array of arguments to trigger() which will be passed to the event handler set in on(). Here is how you do it:

$("button").click(function (event) {
    function cb(prevent) {
        // If the custom event was prevented, prevent original one too
        if (prevent) {
            event.preventDefault();
        }
    }
    $("body").trigger("some-custom-event", [cb]);
})

$("body").on("some-custom-event", function (event, cb) {
  if (Math.random() > .5) {
    console.log("prevent");
    event.preventDefault();
    cb(true);
  } else {
    console.log("allow");
  }
})

You can find out more about trigger() here.

UPDATE:

If you dont want to edit the handlers this is the way to go:

$("button").click(function (event) {
    var event = jQuery.Event('some-custom-event');
    $("body").trigger(event);

    if (event.isDefaultPrevented()) {
        event.preventDefault();
        console.log("Prevented");
    } else {
        console.log("Allowed");
    }
})

$("body").on("some-custom-event", function (event) {
    if (Math.random() > .5) {
        console.log("prevent");
        event.preventDefault();
    } else {
        console.log("allow");
    }
})

event.isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!