Reputation: 23858
Please look at the following code.
var $myInput = $('#myInput'); //select the <input> element
$myInput.on('focus', function(){
console.log('Input focused');
})
Now if I execute the following two lines in IE:
$myInput.trigger('focus');
console.log('Done');
.. the output will be :
Done
Input Focused
This is because, in IE, the triggered events execute asynchronously. But it's the other way around in all the other browsers. Is there any workaround than using the triggerHandle()
or manually calling the event handler function?
Upvotes: 0
Views: 93
Reputation: 23858
Although JS could be seen as single-threaded to scripts, the browser architecture handles things differently. One example is, in some systems, the window.onresize code can fire while you are in the middle executing a script.
Here is is an answer which gives some insight towards that end.
So, when you trigger an event, the browser puts it in the event queue which runs parallel (?the cited answer have some proof for this).
What happens then is:
IE is so slow that event loop gets executed after the current code segment is done with.
Other browsers are fast enough that the even in the loop gets executed immediately.
However, all these imply that there is no guaranteed way to conclude which part of the code will preside the other when you trigger an event through code.
Upvotes: 0
Reputation: 337733
No. There's no way to reliably guarantee the order. The workaround is to not fake events. Place the logic that's executed within the focus
event in its own function, then call that directly.
var $myInput = $('#myInput');
$myInput.on('focus', function() {
foo();
})
foo();
console.log('Done');
function foo() {
console.log('foo');
}
Upvotes: 2