JS

HOW TO CREATE HOOKS IN JAVASCRIPT

Hooks are mechanics to alter or change a process.

Javascript does not suport hooks natively.

We can only simulate hooks using functions and events.

WHAT ARE HOOKS?

01

function doAJAX (url) {   BEFORE HOOK   if (typeof before == "function") { before(); }     DO AJAX CALL    var xhr = new XMLHttpRequest();   xhr.open("POST", url);     AFTER HOOK   if (typeof after == "function")   { xhr.onload = after; }   xhr.send(); }

HOOK USING FUNCTIONS (A)

02

BEFORE HOOK function before () {  document.getElementById("demo")   .style.color = "red"; }   AFTER HOOK function after () {    document.getElementById("demo")   .innerHTML = this.response; }

HOOK USING FUNCTIONS (B)

03

function doAJAX (url) {   BEFORE HOOK   window.dispatchEvent(new    CustomEvent("before"));     DO AJAX CALL    var xhr = new XMLHttpRequest();   xhr.open("POST", url);     AFTER HOOK   xhr.onload = function () {     window.dispatchEvent(new      CustomEvent("aftajax",     {res : this.response }));   };   xhr.send(); }

HOOK USING EVENTS (A)

04

BEFORE HOOK window.addEventListener("b4ajax", function () {   document.getElementById("demoA")   .style.color = "red";  });   AFTER HOOK window.addEventListener("aftajax", function (evt) {   document.getElementById("demoA")   .innerHTML = evt.detail; });

HOOK USING EVENTS (B)

05