Last active
December 27, 2015 14:59
-
-
Save arbalest/7344756 to your computer and use it in GitHub Desktop.
Pass a dot separated string representation of a method (e.g. "MyApp.Utilities.calculateSomething") to be called on the window without using eval.
This file contains 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
/** | |
* Given a string, such as "MyNamespace.MyClass.MyMethod", | |
* this function will check for and execute a corresponding | |
* method on the window. | |
*/ | |
function runAction(action) { | |
var pieces = action.split('.'); | |
var pieceCount = pieces.length; | |
var base = window; | |
for (var i = 0; i < pieceCount; i++) { | |
var piece = pieces[i]; | |
if (i + 1 < pieceCount) { | |
// All but the last piece should be objects | |
if (typeof base[piece] != 'undefined') { | |
base = base[piece]; | |
} else { | |
console.log("Function could not be found."); | |
break; | |
} | |
} else { | |
// The last piece should be a function we can call | |
if (typeof base[piece] == 'function') { | |
base[piece](); // Call the function if it exists on this object | |
} | |
} // end if last piece | |
} // end for each piece | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment