Reputation: 20203
A trigger can be applied at the form level and/or at the item level. What is the best way for it not to be executed the second time?
<form id='f'>
<input id='i' type='text' />
</form>
<script>
validate = function(e) { ... }
reformat = function(e) { ... }
document.getElementById('f').addListener('change',validate,true);
document.getElementById('i').addListener('change',validate,true);
document.getElementById('i').addListener('change',reformat,true);
</script>
Context: a data dictionary says item i
needs to be validated immediately, and the app writer says all items in the form should be validated immediately.
It's the same function, usually called once, but sometimes twice.
What's the best way to keep the validate
function from being executing twice?
Note: e.stopPropagation()
stops all further calls on the click
event, so that the reformat
trigger is no longer called.
Upvotes: 0
Views: 1900
Reputation: 35266
You can add a prop in the event param to make sure it runs once:
validate = function(e) { if (e.done) return; /* code */ e.done = true; }
document.getElementById('f').addListener('change',validate,true);
document.getElementById('i').addListener('change',validate,true);
Although I don't see why you're binding the event twice
EDIT: For cross browserness (read: IE) change it to this:
validate = function(e) {
if ((e = e || window.event).done) return;
/* code */
e.done = true;
}
document.getElementById('f').addListener('change',validate,true);
document.getElementById('i').addListener('change',validate,true);
Upvotes: 2
Reputation: 26873
Basic idea (based on http://www.quirksmode.org/js/events_order.html):
function cancelBubbling(e) {
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
var validate = function(e) {
cancelBubbling(e); // important!
...
};
Upvotes: 1