简体   繁体   中英

insert confirmation behavior for an element while stopping the element's other event handlers

Goal: I'd like to be able to decouple a given element's confirmation behavior from other event handlers it might have bound to it. so given the following trivial example

var someApp = {
  "init": function(){
     $("a").click(someApp.doAnchorStuff); 
     $("button").click(someApp.doButtonStuff); 
     $("#submitButton").click(someApp.doSubmitStuff); 
     $("a, button, #submitButton").click(someApp.confirmAction); 
    }, 
  "doAnchorStuff": function(){//stuff},
  "doButtonStuff": function(){//stuff},
  "doSubmitStuff": function(){//stuff},
  "confirmAction" : function(){
        //intercept the flow of control and freeze everything, no other 
        //handlers on the elements this is being triggered on get called
        //display confirm dialog. 
        //IF user confirms, unfreeze, let the other handlers get triggered. 
        //If Not, do not let other event handlers get triggered
}
}

$(function(){
    someApp.init(); 
});

If this doesn't make sense, I'm happy to clarify.

a NON-working fiddle example :) http://jsfiddle.net/7jbt9/

There are two things you need to do to make this work:

  1. The confirmAction click handler needs to be attached first. Doing this will make it so that it will be executed first in the chain.

  2. Call the stopImmediatePropagation() method on the event object passed to the callback function. This will stop any other callbacks for that event from being executed.

 "confirmAction": function(e) { if (!confirm("Continue?")) { e.stopImmediatePropagation(); } } 

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