Reputation: 37328
I am working on top of existing JavaScript (that I cannot alter) and need to check something on submit.
If my condition is true, no other submit handlers should be applied.
If my condition is false, all other submit handlers shall be applied.
What I have tried so far:
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);
}
});
Now events
is always empty at that point.
It is empty as soon as I call form.off('submit')
and I didn't get it to work with deep cloning either.
Update: In this jsfiddle you see that both events are fired. I want one (preferably one that i add LAST) to be fired and prevent the other one from firing.
Upvotes: 0
Views: 205
Reputation: 1
Try utilizing $.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/
Upvotes: 1
Reputation: 388316
If I got your requirement correctly, you can try a nasty hack like
//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);
Demo: Fiddle
Upvotes: 1