cieunteung
cieunteung

Reputation: 1791

Javascript Class return array, create library like jQuery

I'm creating javascript library like jQuery, I have successfully adding prototype html() but if I call it with $(selector) it return object like {'el' : [array]} and if change in function to return this.el; it return array but I can't call .html().

How it can return [array] instead without breaking prototype?

window.$ = function(selector) {
  if (!(this instanceof $)) {
    return new $(selector);
  }
  this.el = [];
  this.html = function(str) {
    this.el.forEach(function(el) {
      el.innerHTML = str;
    });
  };

  (function(self) {
    for (var eList = document.querySelectorAll(selector), i = eList.length - 1; i > -1; i--) {
      self.el[i] = eList[i];
    }
  })(this);
 
  return this;
};

$('#test').html('BBBBB')
console.log($('#test')[0])
<div id="test">AAAAAAA</div>

Upvotes: 1

Views: 188

Answers (2)

cieunteung
cieunteung

Reputation: 1791

finally it solved by looking Zepto source code, the magic to convert object to array is you have to create $.prototype.splice, it copied from the Array.splice

class return array

// only load if no jQuery on the page
if (window.$ === undefined) window.$ = (function () {
    var $, zepto = {}, emptyArray = [];

    function Z(dom, selector) {
        var i, len = dom ? dom.length : 0;
        for (i = 0; i < len; i++) this[i] = dom[i];
        this.length = len;
        this.selector = selector || '';
    }
    Z.prototype = {
        splice: emptyArray.splice,
        forEach: emptyArray.forEach,
        html: function (str) {
            this.forEach(function (el) {
                el.innerHTML = str;
            });
        }
    };
    zepto.Z = function (dom, selector) {return new Z(dom, selector);};
    zepto.init = function (selector, context) {
        if (!selector) return zepto.Z();
        var dom = document.querySelectorAll(selector);
        return zepto.Z(dom, selector);
    };
    $ = function (sel, ctx) {return zepto.init(sel, ctx); };

    return $;
})();

$('.test').html('DDDDD');
console.log($('.test'));
<div class="test"> AAAA </div>
<div class="test"> BBBB </div>
<div class="test"> CCCC </div>

Upvotes: 1

Kolzar
Kolzar

Reputation: 873

 window.$ = function(selector) {
      var x = [];
      x = document.querySelectorAll(selector);
      console.log(x);
      return x;
    };
NodeList.prototype.html = function(str) {
	console.log(this);
	this.forEach(function(el){
    	el.innerHTML = str;
    });
}


console.log($('#test').html('BBBBB'))
<div id="test"></div>

I extended the html method inside the NodeList array. tell me if it can fit you.

Upvotes: 1

Related Questions