简体   繁体   中英

Controlling event firing sequence in Javascript

The question may sound bit silly but I'm really not able to get any concrete solution for it.

We are revamping an existing legacy application that has huge set of forms and many elements associated to each forms. In most cases, 'onblur' event is associated to one element and 'onclick' event is associated to other lookup related element.

The legacy application was supported only in IE that uses modal dialog to display validation message which use to freeze the code flow till the user action if performed. But in the revamped application which has chrome support, the modal windows are not applicable and the code flow freeze is mimicked using promises.

The problem now with the new approach is when the user enters some invalid data in one element and try clicking on the other lookup element, the 'onblur' event on first element and the 'onclick' event on second element is fired concurrently resulting in multiple windows (one for validation and one for lookup) Is there any way to avoid 'onclick' event firing that happens after 'onblur' event firing? Is it possible to avoid concurrent event firing?

NOTE: There may be some tweaks like adding timeout and moving validation logic inside 'onclick' event of second element to resolve this issue. But unfortunately I will not be able to do this as its a legacy application and the volume of changes to be done across the application is huge.

Sample code to explain the problem:

<html>
    <head><title>Test</title></head>
    <body>
        <input type="text" onblur='setTimeout(function(){window.open("http://www.google.com", "BlurWindow","");},5000)' /> 
        <input type="button" onclick='setTimeout(function(){window.open("http://www.bing.com", "ClickWindow","");},5000)' value="popup"  />
    </body>
</html>

When I key-in some text in textbox and click on popup button, both 'onclick' and 'onblur' event is fired. I need some way to handle concurrent event firing. Is it possible?

We were not able to control the sequence of event firing. Hence we did a workaround to resolve the problem. We are capturing the current focused element in a variable and onclick of any other button element, we are blocking the onclick event of the button from firing if the focused element variable is not null.

Pseudocode as follows:

To capture focused element:

$(":input[type=text]").on('focusin', function () { window.top.prevFocusField = $(this); });

To block onclick action:

if (window.top.prevFocusField != null) { return; }

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