2

Is it possible to create a hook system in javascript as like as php ?

for an example ----

function myjsfunction(){

    call_my_function('handle_name');

}

now whatever function people add with 'handle' name it should get executed there.

like

add_to_function('handle_name', function(){alert('hi')});
add_to_function('handle_name', function(){alert('hello')});

both these functions should execute

2
  • So you are looking for js and php answer? Commented Jul 12, 2017 at 10:16
  • js anwer actually Commented Jul 12, 2017 at 10:18

1 Answer 1

4
var hooks = {};

function add_to_function(name, func) {
  if(!hooks[name]) hooks[name] = [];
  hooks[name].push(func);
}

function call_my_function(name, ...params){
  if(hooks[name]) 
     hooks[name].forEach(func => func(...params));
}

As functions are first class in js you can simply store them in an object.

Usecase:

add_to_function("log", console.log.bind(console, "this will log "));

call_my_function("log", "sth cool!");

Implementation with an IIFE:

http://jsbin.com/joxigabeyi/edit?console

Sign up to request clarification or add additional context in comments.

3 Comments

WOW !!! going to try now, but is it possible avoiding that var hooks user defined variable ? means something global like dom or anything else... so that it will not be dependent of that user variable initialization
IIFE ? i am really not aware of this :(
@alice see updated snippet. BTW Immediatly Invoked Function Expression...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.