georgesamper
georgesamper

Reputation: 5179

querySelectorAll in library

I have this code:

(function (window, document, undefined) {

  var g = function (sel) {

    return {

      selector: document.querySelector(sel),

      on: function (evt, fn) {
        if (this.selector) this.selector.addEventListener(evt, fn, false);
        return this;
      }
    };
  };

  window.g = window._ = g;

})(this, document);

How do I use querySelectorAll instead of querySelector in this context, so that I can select multiple elements. Especially considering there will be multiple methods like on. How do I loop through all the elements and return them to the method it calls.

Upvotes: 0

Views: 209

Answers (1)

amakhrov
amakhrov

Reputation: 3939

selector: document.querySelectorAll(sel),
on: function (evt, fn) {
    if (this.selector) {
        for (var i=0, len=this.selector.length; i < len; i++)
            this.selector[i].addEventListener(evt, fn, false);
    return this;
}

If you have to re-use that loop in many methods, just create a wrapper, something like that

selector: document.querySelectorAll(sel),
forEach: function (codeToApply) {
    for (var i=0, len=this.selector.length; i < len; i++)
            codeToApply.call(this, this.selector[i]);
},
on: function (evt, fn) {
    if (this.selector) {
        this.forEach(function (element) {
            element.addEventListener(evt, fn, false);
        }
    return this;
}

Upvotes: 1

Related Questions