简体   繁体   中英

What is the best way to prevent the same trigger function from executing twice?

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.

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

DEMO

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

Edited DEMO

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!

    ...
};

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