09. Implementing each() method

 247 total views,  1 views today

Step 9: each method()

(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) {  // BEGIN Q
    
    this.nodes = [];  // array to store query results
    
    if (!(this instanceof Q)) {
      return new Q(selector);
    }
    if (typeof selector === "function") {
      return handleDOMReady(selector);
    }
    
    // HTMLElements and NodeLists are wrapped in nodes array
    if (selector instanceof HTMLElement || selector instanceof NodeList) {
      this.nodes = selector.length > 1 ? [].slice.call(selector) : [selector];
    } else if (typeof selector === 'string') {
        if (selector[0] === '<' && selector[selector.length-1] === '>') {
          this.nodes = [createNode(selector)];
        } else {
          this.nodes = [].slice.call(document.querySelectorAll(selector));
        }
    }
    
    // Add nodes to instace of Q(this)
    if (this.nodes.length) {
      this.length = this.nodes.length;
      for(let i = 0; i < this.nodes.length; i++) {
        this[i] = this.nodes[i];
      }
    }
  } // END - Q
  
  // todo
  // Get the prototype (jquery trick)
  Q.fn = Q.prototype;
  
  Q.fn.each = function (callback) {
    for(let i = 0; i < this.length; i++) {
      callback.call(this, this[i], i);
    }
    return this;
  }
  
  function createNode(html) {
    let div = document.createElement('div');
    div.innerHTML = html;
    return div.firstChild;
  }
  
  window.Q = Q;
  
}(window));

Example => Step 9 => each method

Q(() => {
  test("each() method", function() {
    //callback.call(this[i], this, i);
    let $ul = Q(".critical");
    $ul.each((ele, index) => {
      console.log("each: ", ele, index);
    });
  });
});