Skip to content

Instantly share code, notes, and snippets.

@wp-kitten
Created October 7, 2018 15:15
Show Gist options
  • Save wp-kitten/60f297331a716b8ccef90944a1a6c51e to your computer and use it in GitHub Desktop.
Save wp-kitten/60f297331a716b8ccef90944a1a6c51e to your computer and use it in GitHub Desktop.
Utility object to add wp-like actions
(function ($) {
"use strict";
/**
* Holds the list of all registered actions
* @see this.addAction
* @see this.hasAction
* @see this.doAction
* @type {{}}
*/
var actions = {};
/**
* Utility object to add wp-like actions
* @type {{_sprintf: jQuery.AfsUtil._sprintf, addAction: jQuery.AfsUtil.addAction, doAction: jQuery.AfsUtil.doAction, hasAction: (function(*): boolean), removeAction: jQuery.AfsUtil.removeAction}}
* @usage addAction('action-name', fn( [arg1,arg,2] ) );
* @usage doAction( 'action-name', fn( arg1, arg2,...))
*/
$.AfsUtil = {
/**
* Replace the indexed placeholders from the provides string with the replacements from data
*
* sprintf("This is a {0} {1} test", ["Hello", "World"]);
* sprintf("This is a {p1} {p2} test", { p1: "Hello", p2: "World" });
*
* @param {string} str
* @param {{}|[]} data
* @return {*}
*/
_sprintf: function (str, data) {
if (typeof str === 'string' && (data instanceof Array)) {
return str.replace(/({\d})/g, function (i) {
return data[i.replace(/{/, '').replace(/}/, '')];
});
}
else if (typeof str === 'string' && (data instanceof Object)) {
for (var key in data) {
return str.replace(/({([^}]+)})/g, function (i) {
key = i.replace(/{/, '').replace(/}/, '');
if (!data[key]) {
return i;
}
return data[key];
});
}
}
return false;
},
addAction: function (name, callback) {
if (!actions[name]) {
actions[name] = [];
}
actions[name].push(callback);
},
/**
*
* @param {String} name
* @param {[]}args
*/
doAction: function (name, args) {
if (actions[name] && actions[name].length > 0) {
$.each(actions[name], function (a, fn) {
if (typeof(fn) === 'function') {
//#! The first argument MUST be the scope of "this"
fn.apply((args ? args[0] : this), args || []);
}
});
}
},
hasAction: function (name) {
return (!!actions[name]);
},
removeAction: function (name) {
if (this.hasAction(name)) {
delete(actions[name]);
}
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment