在停止元素的同时插入元素的确认行为'的其他事件处理程序

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

本文关键字:元素 事件处理 程序 其他 确认 插入      更新时间:2023-09-26

目标:我希望能够将给定元素的确认行为与它可能绑定的其他事件处理程序解耦

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(); 
});

如果这没有道理,我很乐意澄清。

一个非工作小提琴的例子:)http://jsfiddle.net/7jbt9/

要实现这一点,需要做两件事:

  1. 需要首先附加confirmAction单击处理程序这样做将使它在链中首先执行。

  2. 对传递给回调函数的事件对象调用stopImmediatePropagation()方法这将停止执行该事件的任何其他回调。

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