开发者

Can a DOM event be allowed its default behaviour after it's been stopped or prevented?

开发者 https://www.devze.com 2023-03-11 19:20 出处:网络
I\'d like to allow the default event behaviour of certain elements (ie. <a> and <form>) until I can be certain that items in the Google Analytics queue have been processed.

I'd like to allow the default event behaviour of certain elements (ie. <a> and <form>) until I can be certain that items in the Google Analytics queue have been processed.

I've seen many methods that involve adding an event listener that stops the passed event (event.stop() or event.stopPropagation() or return false), or prevents its default behaviour (event.preventDefault()). This then requires that the behaviour be somehow re-written, instead of just passing/ac开发者_如何学Pythontivating/releasing the original event.

For example, with mootools, I could use the following event handler on <a id="special-a-element"> to push and process a GA event before redirecting to the target document:

$('special-a-element').addEvent('click', function() {
    var url = this.get('href');
    _gaq.push(['_trackEvent', 'category', 'action']);
    _gaq.push(function() { document.location = url; });
    return false;
});

Here, the document.location recreates what the browser might do if it were allowed to deal with the click event I've stopped (with return false); this seems unnecessary. What if special-a-element had target = "_blank"? The listener would not open the link in a new window, but in the current one (because of document.location).

So I would like to allow the default behaviour without stopping it then re-implementing it. Any suggestions?


Couldn't you do something like...

$(...).addEvent(function(e) {
  setTimeout(function() {
    e.target.parentNode.dispatchEvent(e)
  }, 1000);

  // cancel the event
  return false;
})


You could implement a sleep function and use it like this:

$(document).ready(function(){
    $("a").click(function(){
        // do other stuff here
        sleepUntilGAReady();
    });
});

function sleepUntilGAReady() {
    var GAReady = false;
    while (!GAReady) {
         sleep(500);        
         GAReady = /* check if it's done */;
    }
}

function sleep(miliseconds) {
    var start = new Date().getTime();
    while (new Date().getTime() - start < miliseconds); 
}

Or, if you don't need the time delay, just do it like in sleep() - while (!/* check if GA is ready */); in the end of the event you want to delay.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号