How to Create Hooks In Javascript (Simple Examples)

Welcome to a tutorial on how to create hooks in Javascript. You may have heard of hooks from other tutorials, frameworks, or have already used them in other programming languages. But just what are hooks? How do we use and implement hooks in Javascript?

Hooks are usually used to intercept procedures, and possibly change the way they act. But hooks are not natively supported in Javascript, we can only simulate hooks using functions and events.

 

Just how is this done? Let us walk through some examples in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Hook Basics Hook Examples
Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

HOOK BASICS

Before we dive into any code, here is a section on the basics of hooks – What are hooks, what they do, and why we need them. Feel free to skip if you are already a code ninja.

 

WHAT IS A HOOK?

Let me just do a quick quote from Wikipedia:

In computer programming, the term hooking covers a range of techniques used to alter or augment the behaviour of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components.

Several other different geeky websites also offer a similar definition, but maybe a simple example will illustrate that better. Now, let us say that we have a generic function that will do an AJAX call to the server.

That will work, but it is not the most elegant solution. AJAX is asynchronous and runs in parallel. So what if the user clicks on the submit button multiple times? End up with multiple submissions? Also, there is no feedback on whether the AJAX process is successful or not. So here is where hooks come into play.

We can add a hook before the AJAX call to disable the submit button, to prevent the user from submitting multiple times. We can also add another hook after the AJAX call to show the results of the process, to re-enable the submit button.

 

 

WHY DO WE NEED HOOKS?

Now, some of you guys may be thinking – Isn’t that stupid? We could have just created a single simple function to do all of these. Why go through all the trouble to create so many functions, so much of all these roundabout useless hooks thing?

The keywords here are reusability, extendable, and flexibility. The AJAX function here is a common core process – We use it whenever we need to communicate with the server, and it could be shared among hundreds of other functions; We do not want to modify this core function, but to extend the usability of it, which is where hooks step in.

 

HOOKS, CALLBACK, EVENTS

Some of you advanced code ninjas may be a little confused right now – Isn’t the above example the same as a callback or event? Well yes, these 3 are relatives but totally different mechanics altogether:

  • Events are fired when certain things happen – Mouse click, keyboard press, finished loading, etc…
  • Callbacks are functions that we put into another function to complete a certain task.
  • Hooks intercept the process and may interrupt the normal process.

So before the hater flamer Internet troll things start to throw smart-aleck comments – Javascript does not have a native hook implementation. The only “hook” that we can “build” in Javascript is achieved with events and/or callbacks. Also, the “interrupt normal process” part cannot be fully replicated in Javascript.

 

 

JAVASCRIPT HOOK EXAMPLES

Now that we are done with the basics, let us go into simple examples of how we can implement hooks in Javascript.

 

1) HOOKS USING FUNCTIONS

1a-hook-function.html
<p id="demoA"></p>

<script>
// (A) "HOOKED" AJAX FUNCTION
function doAJAX (url) {
  // (A1) BEFORE HOOK
  if (typeof before == "function") { before(); }
 
  // (A2) DO AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);
 
  // (A3) AFTER HOOK - SERVER RESPONSE
  if (typeof after == "function") { xhr.onload = after; }
  xhr.send();
}
 
// (B) CREATE HOOKS
function before () {
  document.getElementById("demoA").style.color = "red";
}
function after () {
  document.getElementById("demoA").innerHTML = this.response;
}
 
// (C) GO!
doAJAX("1b-dummy.html");
</script>

Yes, this is the “exact implementation” of the above example in the basics section.

  • function doAJAX() does an AJAX call to POST some data to a specified URL.
  • Hooks are simulated using before() and after(). Altering what doAJAX() does before the AJAX call, and after the server responds.
  • I.E. We use if (typeof XYZ == "function") { XYZ(); } to check if before() and after() exists and call them accordingly.

 

 

2) HOOKS USING EVENTS

2-hook-event.html
<p id="demoA"></p>

<script>
// (A) "HOOKED" AJAX FUNCTION
function doAJAX (url) {
  // (A1) BEFORE HOOK
  window.dispatchEvent(new CustomEvent("b4ajax"));
 
  // (A2) DO AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);

  // (A3) AFTER HOOK - SERVER RESPONSE
  xhr.onload = function () {
    window.dispatchEvent(new CustomEvent("aftajax", {detail: this.response}));
  };
  xhr.send();
}

// (B) SET HOOKS
window.addEventListener("b4ajax", function () {
  document.getElementById("demoA").style.color = "red";
});
window.addEventListener("aftajax", function (evt) {
  document.getElementById("demoA").innerHTML = evt.detail;
});
 
// (C) GO!
doAJAX("1b-dummy.html");
</script>

This should be self-explanatory – Instead of using functions, we dispatch custom events to simulate hooks here.

 

 

3) MULTIPLE HOOKS HANDLER

3-multi-hook.html
<p id="demoA"></p>

<script>
// (A) MULTIPLE HOOKS HANDLER
// Credits to https://jsbin.com/joxigabeyi/edit?js,console
var hooks = {
  // (A1) CURRENT HOOK QUEUE
  queue : {},

  // (A2) ADD FUNCTION TO QUEUE
  // name : name of function to add hook to
  // fn : function to call
  add : function (name, fn) {
    if (!hooks.queue[name]) { hooks.queue[name] = []; }
    hooks.queue[name].push(fn);
  },

  // (A3) CALL A HOOK
  // name : name of function to add hook to
  // params : parameters
  call: function (name, ...params) {
    if (hooks.queue[name]) {
      hooks.queue[name].forEach(fn => fn(...params));
      delete hooks.queue[name];
    }
  }
};

// (B) "HOOKED" AJAX FUNCTION
function doAJAX (url) {
  // (B1) BEFORE HOOK
  hooks.call("beforeAJAX");

  // (B2) DO AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);

  // (B3) AFTER HOOK - SERVER RESPONSE
  xhr.onload = function(){
    hooks.call("afterAJAX", this.response);
  };
  xhr.send();
}

// (C) SET HOOKS
hooks.add("beforeAJAX", function () {
  document.getElementById("demoA").style.color = "blue";
});
hooks.add("beforeAJAX", function () {
  document.getElementById("demoA").style.background = "lightblue";
});
hooks.add("afterAJAX", function (res) {
  document.getElementById("demoA").innerHTML = res;
});
hooks.add("afterAJAX", function () {
  document.getElementById("demoA").innerHTML += "FOO BAR!";
});

// (D) GO!
doAJAX("1b-dummy.html");
</script>

Credits go to this hook snippet on JSBIN. In this final so-called “advanced example”, we address one issue with the above simple examples – What if we want to run more than one hook?

  • We introduce a var hooks hook handler.
  • Basically, we use hooks.add() to store hooks functions into hooks.queue.
  • Use hooks.call() to run the respective hooks.

 

USEFUL BITS & LINKS

That’s all for the code, and here is a small extra that may be useful to you.

 

THESE ARE JUST FUNCTIONS & EVENTS!

I can smell angry and toxic trolls. This is so dumb! All examples are just using functions and events, this is not a hook! Yep, just to repeat the introduction – Hooks are not natively available in Javascript. We can only simulate “hook-like” behaviors using various techniques. So go ahead, these are technically not hooks.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

How To Create Hooks In Javascript (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand hooks, and improve your project. If you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “How to Create Hooks In Javascript (Simple Examples)”

  1. Hi, thank you for this example, it was straight-forward and concise. I had two questions:
    1. Would a Set work better for the hooks rather than an Array? Or is it a wash?
    2. Why are you deleting the hooks entry after the function call?

    1. 1) Don’t quite catch what you mean. But hooks.queue is an object of arrays.

      2) No right-or-wrong here, but think in the opposite direction too. Why and when do you want to keep them? Running the same set of hooks for 2 different processes makes no sense. But if it is a repeated process – The same set of hooks make sense.

Leave a Comment

Your email address will not be published.