cotut
cotut

Reputation: 131

How to create shorter equivalent for addEventListener

I want to create a short function for addEvenTListener like jQuery does. I have seperate functions for select and event listener. But I want to be able to use $(selector).on instead of on(event, elem, callback, capture). How can I achieve that?

function $ (selector, scope) {
    scope = scope ? scope : document;
    return   scope.querySelector(selector);
};

var on = function (event, elem, callback, capture) {

    if (typeof (elem) === 'function') {
        capture = callback;
        callback = elem;
        elem = window;
    }
    capture = capture ? true : false;
    elem = typeof elem === 'string' ? document.querySelector(elem) : elem;
    if (!elem) return;
    elem.addEventListener(event, callback, capture);
};

Upvotes: 1

Views: 1545

Answers (3)

BeesWax
BeesWax

Reputation: 112

Node.prototype.listen = Node.prototype.addEventListener;

creates an alias or new reference.

// example

el.listen('click', function(){
   // etc.
})

Upvotes: 1

Andrew Svietlichnyy
Andrew Svietlichnyy

Reputation: 751

JQuery returns an array of elements wrapped in jQuery object that provides useful methods in its prototype. So, simplified, it works similar to the code below. The last line is the way you want to attach event listeners to elements (if I understand correctly).

function $(selector, scope){
  let z = Object.create($.prototype);
  z.e = (scope || document).querySelector(selector);
  return z;
}

$.prototype.on = function(event, callback, capture){
  return this.e.addEventListener(event, callback, capture);
}

$("button").on("click", ()=>console.log("Clicked!"));
<button>Click</button>

Upvotes: 3

M&#225;t&#233; Safranka
M&#225;t&#233; Safranka

Reputation: 4116

jQuery returns a wrapper object which exposes the methods .on(), .attr(), .prop() etc, instead of the actual HTMLElement instance. So, one way you can accomplish that is to do the same.

Another, technically feasible way is to amend the prototype of the HTMLElement class:

HTMLElement.prototype.on = function(event, callback, capture) { ... };

Note, however, that manipulating prototypes you didn't create yourself is very much not recommended. It can easily break predefined behavior, perhaps not now but in future versions of JavaScript.

Upvotes: 2

Related Questions