Last active
June 24, 2021 02:05
-
-
Save wp-kitten/40e2d711e63e1f5f31fa660061fe82fd to your computer and use it in GitHub Desktop.
WordPress-like actions for javascript
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
/** | |
* Global object storing all registered actions | |
* @type {*[]} | |
* @public | |
*/ | |
window.__actions__ = []; | |
/** | |
* Register an action | |
* @param actionName | |
* @param callback | |
* @param priority | |
*/ | |
function add_action(actionName, callback, priority) { | |
if ( !priority || priority < 0 ) { | |
priority = 10; | |
} | |
if ( priority > 100 ) { | |
priority = 100; | |
} | |
var actions = window.__actions__; | |
if ( typeof actions[actionName] == 'undefined' ) { | |
actions[actionName] = []; | |
} | |
if ( typeof actions[actionName][priority] == 'undefined' ) { | |
actions[actionName][priority] = [] | |
} | |
actions[actionName][priority].push( callback ); | |
} | |
/** | |
* Trigger all callbacks registered for the specified action based on their priority | |
*/ | |
function do_action(/* actionName [, param1, param2, ...]*/) { | |
if ( arguments.length === 0 ) { | |
return; | |
} | |
var args = Array.prototype.slice.call( arguments ), | |
actionName = args.shift(), | |
_this = this; | |
var actions = window.__actions__; | |
if ( !actions[actionName] || actions[actionName].length === 0 ) { | |
return; | |
} | |
//#! Order by priority | |
var priorities = Object.keys( actions[actionName] ); | |
//#! Do actions | |
priorities.forEach( function (priority, v) { | |
actions[actionName][priority].forEach( function (callback, v) { | |
callback.apply( _this, args ); | |
} ); | |
} ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment