Last active
December 9, 2015 23:08
-
-
Save davidkelley/4342647 to your computer and use it in GitHub Desktop.
This coffeescript snippet creates a modularised event delegator for usage in conjunction with RequireJS. Backward compatibility support to IE8 only.
This file contains hidden or 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
define [], -> | |
# Handles site-wide event delegations for all elements. | |
# @param selector The CSS-style element selector. | |
# @param event The event to bind to, click, hover, mouseenter, etc. | |
# @param handler The handler function to execute on event firing | |
# return void | |
(selector, event, handler) -> | |
# Define function to wrap the handler function in | |
fnc = (e) -> | |
# Get the events source element. Fallback for IE | |
src = e.target || e.srcElement | |
# Bind the element matcher. Determines events | |
# source element by matching the defined selector with it | |
matcher = src.webkitMatchesSelector || src.mozMatchesSelector || (selector) -> | |
# Find all elements matching the selector | |
elements = document.querySelectorAll selector | |
# Attempt to find the source element in matching elements | |
return true for element in elements when element is this | |
# Failed, dont call the handler | |
return false | |
# Call the handler only if a matching element was found | |
while src != document | |
match = matcher.call src, selector | |
handler.call src, e if match | |
break if match | |
src = src.parentNode | |
# Bind the event, fallback for IE | |
if document.addEventListener then document.addEventListener event, fnc else document.attachEvent "on"+event, fnc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment