在条件下触发所有事件,否则触发 none

On condition fire all events, else fire none

我正在现有 javascript(我无法更改)的基础上工作,需要检查 提交.

如果我的条件成立,则不应应用其他提交处理程序。

如果我的条件为假,将应用所有其他提交处理程序。

到目前为止我尝试过的:

var form = jQuery('form'),
that = this,
events = $._data(form[0]).events['submit'];

form.off('submit');
form.on('submit', function (event) {
    if (that.myCondition()) {
        event.preventDefault();
        event.stopPropagation();
        return false;
    } else {
       console.log('Call these: ', events);
    }
});

现在 events在那一点上总是空的。

我一调用它就空了form.off('submit')而且我也没有让它与深度克隆一起工作。

更新: 在此 jsfiddle 中,您会看到两个事件都被触发了。我想要一个(最好是我最后添加的一个)被解雇并防止另一个被解雇。

如果我正确地理解了你的要求,你可以尝试像

这样的讨厌的黑客攻击
//the counter is just to demonstrate any condition
var counter = 0;
$('form').submit(function (e) {
    console.log('master handler form');
    //if counter is a multiple of 2 prevent other handlers
    if (++counter % 2 == 0) {
        //stop other submit handlers attached to the form
        e.stopImmediatePropagation();
        //stop propagation and default behavior
        return false;
    }
});

var form = jQuery('form'),
    events = $._data(form[0]).events['submit'];

var tmp = events.pop();
events.unshift(tmp);

演示:Fiddle

尝试利用 $.Callbacks("stopOnFalse")

var callbacks = $.Callbacks("stopOnFalse");
// if `input.val().length === 0` `fn1` not called
var fn2 = function fn2(event) {
    // `this`:`form` element
    // console.log(this); 
    event.preventDefault();
    event.stopPropagation();
    console.log('1st submit called:', input.val().length);
    if (input.val().length === 0) {
        // `input.val().length === 0`
        // do stuff , do not do stuff ? here
        output1.html('Input needed!');
        // reset `output2` `html`
        output2.html("...");
        // return `false` to "stop" `callbacks` queue;
        // `fn1` not called
        return false;
    }
};
// if `input.val().length !== 0` , `fn1` called,
// else `fn1` not called
var fn1 = function fn1(event) {
    // do stuff 
    // call `event.preventDefault();` , here, if needed;
    // else call `output2.html('success!');` , submit form
    // event.preventDefault();
    console.log('2nd submit called:', input.val().length);
    output2.html('success!');
};
// add `fn2` , `fn1` to `callbacks` queue
callbacks.add(fn2, fn1);
// call both `fn2` , `fn1` if `input.val().length !== 0` ,
// else, do not call `fn1`
form.on('submit', function (event) {
    // `fire` `callbacks` `fn2` , `fn1` with context `this`:`form` ,
    // pass `event` as parameter to `fn2`, `fn1`
    callbacks.fireWith(this, [event])
});

jsfiddle http://jsfiddle.net/bkdm7fzt/3/