diff --git a/js/test.js b/js/test.js index df720b30cc699cffc4567b579b848b7b53e21465..48103e9040c9dc62c0f5dd96b57b5f399c7d1511 100644 --- a/js/test.js +++ b/js/test.js @@ -9,6 +9,12 @@ if(!mu.exists(window.muTest)){ console.log(data); } }); + }, + delegateEvent: function(){ + mu('#delTest').on('click', '.clickme', function(e){ + console.log(this); + console.log(e); + }); } } } diff --git a/js/tinyDOM.js b/js/tinyDOM.js index 1e29fac0f377b08388862f47dcd57edaa6fedcd6..d5d118a66b992e883a5b516ebd7383430e6ad82d 100644 --- a/js/tinyDOM.js +++ b/js/tinyDOM.js @@ -1,4 +1,18 @@ (function(){ + + /* + * Polyfill from https://gist.github.com/elijahmanor/6452535 + */ + if (Element && !Element.prototype.matches) { + var proto = Element.prototype; + proto.matches = proto.matchesSelector || + proto.mozMatchesSelector || proto.msMatchesSelector || + proto.oMatchesSelector || proto.webkitMatchesSelector; + } + /* + * End Polyfill + */ + var tinyDOM = function(selector){ return new tinyDOMFunction(selector); } @@ -58,10 +72,32 @@ }); return this; }, - on: function(ev, fn){ - this.each(function(i, e){ - e.addEventListener(ev, fn); - }); + on: function(ev, del, fn){ + if(typeof(del) === 'string'){ + this.each(function(i, e){ + e.addEventListener(ev, function(firedevent){ + var target = firedevent.target; + var matched = false; + do { + if(target && target.matches(del)){ + fn.call(target, firedevent); + matched = true; + } else { + target = target.parentNode; + if(!target || !target.matches){ + matched = true; + } + } + } while(matched !== true); + + }); + }); + } else { + var fn = del; + this.each(function(i, e){ + e.addEventListener(ev, fn); + }); + } return this; }, first: function(){ diff --git a/test.html b/test.html index 06eda269f5251aaeb693588e9c877f37243e2107..89f6c256d267432517b7a619edb905f1215275c9 100644 --- a/test.html +++ b/test.html @@ -20,8 +20,8 @@ <button id="btn-hide">HIDE THINGS</button> <button id="btn-show">SHOW THINGS</button> - <section class='information' data-href='tests/get.html'> - <h2>About tinyDOM functions</h2> + <section class='information'> + <h2 data-href='tests/get.html'>About tinyDOM functions</h2> <p> tinyDOM operates on dom elements to make it a bit easier to select and manipulate them. It also provides some simple @@ -41,6 +41,18 @@ <ul> <li>.data(<em>attribute</em>)</li> </ul> + + <hr> + + <p> + There are also functions that are invoked directly from the my object, and deal with + things such as ajax requests and json utilities. A few examples of these are + </p> + <ul id='delTest'> + <li class='clickme'>.merge(<em>obj1</em>, <em>obj2</em>)</li> + <li class='noclick'>.exists(<em>obj</em>)</li> + <li class='clickme'>.ajax(<em>params</em>)</li> + </ul> </section> </body> @@ -59,7 +71,7 @@ console.log(this); }); - μ('.information').on('click', function(){ + μ('.information h2').on('click', function(){ var url = μ(this).data('href'); console.log(μ(this).data('href')); μ.ajax({