Sunday, 15 March 2015

jQuery's "on" and "off" in pure native javascript -



jQuery's "on" and "off" in pure native javascript -

i'm looking way represent "on" , "off" capabilities of jquery in pure javascript code.

for example:

jquery("my_selector_here").on("click", function(){ // code here... })

should represented in (total) accurate way, like:

myobj.fn.on = function(){ // pure javascript code here... }

thanks in advance!

the native approach using dom's element.prototype.addeventlistener method. looks pretty straight forwards like

elem.addeventlistener('click', function( event ) { }, false);

that is, beside other magic, jquery phone call underneath. biggest issue libraries deal with, old'ish net explorer had different syntax adding events on elements. used elem.attachevent method, had slight differences.

naively spoken, add together elements.prototype. instance

element.prototype.on = function( name, callback ) { this.addeventlistener( name, callback, false ); };

..and can utilize like

document.body.on('click', function() { // code });

ref.: addeventlistener, jquery .on

javascript jquery native

No comments:

Post a Comment