04. Create instance of ‘Q’ library

 279 total views,  1 views today

In this lesson we will create an instance of Q() library.

Step 4: returns new Q(), if invoked Q as a function.

We want to support two method of invocation of our library as shown below.

let $ = Q("#tasks");  // OR 
let $ = new Q("#tasks");

Either of the above approach should work. Let’s write the code.

(function (window, undefined) {
  let domReadyQueue = [];  // FIFO
  
  // Define a ready handler
  const handleDOMReady = (fn) => {
    return document.readyState === "complete"
      ? fn.call(document)
      : domReadyQueue.push(fn);
  }
  
  document.addEventListener("DOMContentLoaded", function onDOMReady() {
    document.removeEventListener("DOMContentLoaded", onDOMReady); 
    while(domReadyQueue.length) {
      domReadyQueue.shift().call(document);
    }
  })
    
  function Q (selector) {
    if (!(this instanceof Q)) {
      return new Q(selector);
    }
    if (typeof selector === "function") {
      return handleDOMReady(selector);
    }
  } 
  window.Q = Q;
}(window));

Here in the constructor function Q() we check if the instance is of not type Q we create a new instance and return back to the caller.

Example -> Step 4 => return new Q() if instance not of  type ‘Q’

Let’s do a quick test.

Q(() => {
  let $ = Q("#tasks");
  let $ = new Q("#tasks");
  console.log("q: instance: ", $ instanceof Q); // returns => true
  console.log("q: instance: ", $ instanceof Q); // returns => true
});