ttsvetko
6/9/2013 - 7:22 AM

Simple 'onbeforeunload' multiple handler. It assigned a basic function to 'onbeforeunload' method of window object and provide ability to at

Simple 'onbeforeunload' multiple handler. It assigned a basic function to 'onbeforeunload' method of window object and provide ability to attache multiple functions to be called when 'onbeforeunload' event is called.

(function (win) {
  var funcArr = [],
      isFunction = function (value) { return (value && (value).constructor === Function); },
      isString = function (value) {return (value && (value).constructor === String); };
  win.onbeforeunload = function() {
    var func,
        result;
    while (func = funcArr.shift()) {
      if (func && isFunction(func)) {
        result = func();   
        if (result !== undefined && isString(result)) {
          break;
        }
      }
    }
    return result;
  };
  win.addOnBeforeUnload = function (func) {
    if (func && isFunction(func)) {
      funcArr.push(func);
    }
  };
}(window));


/* ---------------------------------- TEST ---------------------------------- */
window.addOnBeforeUnload(function() {
  return (Math.round(Math.random())) ? "test" : undefined;
});

window.addOnBeforeUnload(function() {
  return (Math.round(Math.random())) ? "test2" : undefined;
});

window.addOnBeforeUnload(function() {
  return (Math.round(Math.random())) ? "test3" : undefined;
});

window.addOnBeforeUnload(function() {
  return (Math.round(Math.random())) ? "test4" : undefined;
});