Tuesday, May 28, 2013

Call-It-Once JavaScript Function Wrapper

Just a quick utility function that makes it easy to wrap another JS function to ensure it is only called once:


var callOnceWrapper = function(f) {
    var called = false;
    return function() {
        if (!called) {
            f();
        }
        called = true;
    };
};


Use it by wrapping your callback that you only want to execute once:
var navigateCallback = callOnceWrapper(function() {
    document.location = event.location;
});
ga('send', {
  'hitType': 'event',
  'eventCategory': 'Flyout Link',
  'eventAction': 'UrlMinusDomainAndServletContext',
  'eventLabel': 'Portlet Name',
  'hitCallback': function() {
      navigateCallback
  }
});            
//Fallback in case hitCallback takes too long to get called, don't want clicks to hang
setTimeout(navigateCallback, 100);

Even though there is potential for navigateCallback to get called twice the wrapper only allows the first invocation through.

No comments: