Skip to content

Instantly share code, notes, and snippets.

@wp-kitten
Last active June 24, 2021 02:05
Show Gist options
  • Save wp-kitten/40e2d711e63e1f5f31fa660061fe82fd to your computer and use it in GitHub Desktop.
Save wp-kitten/40e2d711e63e1f5f31fa660061fe82fd to your computer and use it in GitHub Desktop.
WordPress-like actions for javascript
/**
* 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