Y playground 2

Testing the dom selector class based on Proxy object.

by Konrad P

HTML

<div class = 'd1 allDivs'>
 blah1 
</div>

<div class = 'd2 allDivs'>
 blah2
</div>

JavaScript

console.clear();

(function(window) {
  
  class Yes {
  
      constructor(selector){
        this.length = 0;
        this.nodes  = [];
        if(typeof selector === 'string' && selector !== '') {
          //this.nodes = [].slice.call(document.querySelectorAll(selector));
          this.nodes = Array.from(document.querySelectorAll(selector));
        }

		//This is we can access the object with [index]:
        if (this.nodes.length) {
          this.length = this.nodes.length;
          for (var i = 0; i < this.nodes.length; i++) {
            this[i] = this.nodes[i];
          }
        }
      }
      
      //methods:
      forEach (elem) {this.nodes.forEach (elem);return this;}
    
      //traps:	
      
      //target here is *we* - the Yes instance (this), and prop is (string) property being called, a property or method
      get (target, prop) {
      	//console.log('is same:',this === target);//true.
		console.log('::get called, for prop: ', prop);
        return function(...args) {
        	
            console.log('wrapper args:', args);
 			target.forEach((elem) => {
                if(typeof elem[prop] === 'function'){
                    elem[prop](...args);
                }
        	});        

        }        
     }
      
	set (target, prop, value) {
    	//console.log('is same:',this === target);//true.
		console.log('::set called, for prop, val:: ', prop, value);
        target.forEach((elem) => {
            if(typeof elem[prop] !== 'function'){
                elem[prop] = value;
            }
        });            

     }
  }
  
  /////////
  //End of class Yes definition
  
  function yes (selector){
    let yInstance = new Yes(selector);
    return new Proxy(yInstance, yInstance);
  }
  
  //
  Yes.fn = Yes.prototype;
  window.yes = yes;
  
  //E.fn.forEach = function (elem) {this.nodes.forEach (elem);return this;}
  
 
  
})(window);
 
//tests:

//These work...