Created
April 24, 2014 18:47
-
-
Save 0xBADC0FFEE/11265193 to your computer and use it in GitHub Desktop.
$.live() like function in pure js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var live = (function () { | |
var eventRegistry = {}; | |
function dispatchEvent(event) { | |
var targetElement = event.target; | |
eventRegistry[event.type].forEach(function (entry) { | |
var potentialElements = document.querySelectorAll(entry.selector); | |
var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0; | |
if (hasMatch) { | |
entry.handler.call(targetElement, event); | |
} | |
}); | |
} | |
return function (selector, event, handler) { | |
if (!eventRegistry[event]) { | |
eventRegistry[event] = []; | |
document.documentElement.addEventListener(event, dispatchEvent, true); | |
} | |
eventRegistry[event].push({ | |
selector: selector, | |
handler: handler | |
}); | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment