Skip to content

Instantly share code, notes, and snippets.

@JoeSz
Last active November 2, 2016 07:10
Show Gist options
  • Save JoeSz/6aa061ff48eaf1af658d3adf9d71ec37 to your computer and use it in GitHub Desktop.
Save JoeSz/6aa061ff48eaf1af658d3adf9d71ec37 to your computer and use it in GitHub Desktop.
JavaScript Hooks and Filters
/*
* Source: http://stackoverflow.com/questions/20131168/jquery-javascript-hooks/20132960#20132960
* Gist: https://gist.github.com/JoeSz/6aa061ff48eaf1af658d3adf9d71ec37
*
* JavaScript Hooks
* Essentially it's a place in code that allows you to tap in to a module to either provide different
* behavior or to react when something happens.
* (http://stackoverflow.com/questions/467557/what-is-meant-by-the-term-hook-in-programming/467568#467568)
*
* or as Wikipedia says:
* In computer programming, the term hooking techniques used to alter or augment the behavior of
* applications, or of other software components by intercepting function calls or messages or
* events passed between software components. Code that handles such intercepted function calls,
* events or messages is called a "hook".
*/
var filter = {
filters: {},
add: function ( tag, filter ) {
( this.filters[tag] || ( this.filters[tag] = [] ) ).push( filter );
},
apply: function (tag, val, def) {
try {
if ( this.filters[tag] ) {
var filters = this.filters[tag];
for( var i = 0; i < filters.length; i++ ){
val = filters[i](val);
}
} else if ( def ) {
val = def;
}
return val;
} catch ( err ) {
console.log( err );
}
},
remove: function( tag ) {
if( this.filters[tag] ){
delete this.filters[tag];
}
}
};
// Then to add a filter:
filter.add('modify_name', function(name){
name = 'MR. ' + name;
return name;
});
// And to apply the filters:
// Default value if "modify_name" filter and "name" value is not exist, false, 0, null or empty
name = filter.apply('modify_name', name, 'default-value');
// Then to add a "hook":
// (Hook as filter without return a value)
filter.add('modify_hook_name', function(){
// Your code here
});
// Remove filter/"hook"
filter.remove('modify_name');
// And to run the "hook"
filter.apply('modify_hook_name');
// Check if filter exist
if ( typeof filter !== 'undefined' ) filter.apply( 'hook-name' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment