Created
October 7, 2009 16:40
-
-
Save subtleGradient/204192 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Function.safeTry = (function(){ | |
| var currentHandler; | |
| var dispatchFakeEvent; | |
| var currentHandlerResult; | |
| if (document.addEventListener){ | |
| document.addEventListener("fakeEvents", function(){ | |
| currentHandler(); // execute the callback | |
| }, false); | |
| dispatchFakeEvent = function(){ | |
| var fakeEvent = document.createEvent("UIEvents"); | |
| fakeEvent.initEvent("fakeEvents", false, false); | |
| document.dispatchEvent(fakeEvent); | |
| }; | |
| } | |
| else | |
| if (document.attachEvent){ | |
| document.documentElement.fakeEvents = 0; | |
| document.documentElement.attachEvent("onpropertychange", function(event){ | |
| if (event.propertyName == "fakeEvents") | |
| currentHandler(); | |
| }); | |
| dispatchFakeEvent = function(){ | |
| document.documentElement.fakeEvents++; // fire the propertychange event | |
| return currentHandlerResult; | |
| }; | |
| } | |
| return function(handler, shouldCatch){ | |
| if (shouldCatch) { | |
| try{ currentHandlerResult = handler(); } | |
| catch(e){ currentHandlerResult = e; } | |
| } | |
| else { | |
| currentHandler = function(){ | |
| currentHandlerResult = handler(); | |
| }; | |
| dispatchFakeEvent(); | |
| } | |
| return currentHandlerResult; | |
| }; | |
| })(); | |
| Function.prototype.safeTry = function(){ | |
| return Function.safeTry(this); | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Function.safeTry(function(){ | |
| // console.log("Init: 1"); | |
| // DOES_NOT_EXIST++; // this will throw an error | |
| // }); | |
| // | |
| // Function.safeTry(function(){ | |
| // console.log("Init: 2"); | |
| // }); | |
| function PASS(){ console.log('PASS'); return 'Passed!'; } | |
| function FAIL(){ console.log('FAIL'); DOES_NOT_EXIST++; } | |
| // console.log( Function.safeTry(PASS) ); | |
| // console.log( Function.safeTry(FAIL) ); | |
| console.log( PASS.safeTry() ); | |
| console.log( FAIL.safeTry() ); | |
| // console.log( FAIL.safeTry() instanceof Error ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment