Last active
April 12, 2017 20:21
-
-
Save bruslim/482ca841770fc4c34fee04d86066b004 to your computer and use it in GitHub Desktop.
Stupid Jelly - a bean compatible event system that proxies everything to native dom events
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
class Registry { | |
static split(string) { | |
return string.split(' '); | |
} | |
constructor() { | |
Object.defineProperties(this, { | |
map: {value: new WeakMap()} | |
}); | |
} | |
get(el, events) { | |
if (!this.map.has(el)) { | |
this.map.set(el, new Map()); | |
} | |
const entry = this.map.get(el); | |
if (!events) { return entry; } | |
return Registry.split(events).map(event => { | |
if (!entry.has(event)) { | |
entry.set(event, new Set()); | |
} | |
return entry.get(event); | |
}); | |
} | |
delete(el, events) { | |
if (!events) { | |
this.map.delete(el); | |
return; | |
} | |
const entry = this.map.get(el); | |
if (!entry) { return; } | |
Registry.split(events).forEach(event => entry.delete(event)); | |
} | |
} |
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
class StupidJelly { | |
static isSupported(el, event) { | |
const eventName = `on${event}`; | |
const isSupported = (eventName in el); | |
if (isSupported) { return true; } | |
const oldAttribute = el.getAttribute(eventName); | |
el.setAttribute(eventName, 'return;'); | |
const isFunction = typeof el[eventName] === 'function'; | |
if (oldAttribute) { | |
el.setAttribute(eventName, oldAttribute); | |
} else { | |
el.removeAttribute(eventName); | |
} | |
return isFunction; | |
} | |
on(el, events, fn) { | |
if (typeof el.addEventListener === 'function' && typeof events === 'string') { | |
events.split(' ').filter(s => s && s.length).map( | |
s => s.toLowerCase() | |
).filter( | |
s => StupidJelly.isSupported(el, s) | |
).forEach( | |
event => el.addEventListener(event, fn) | |
); | |
} | |
} | |
once(el, events, fn) { | |
const self = this; | |
const handler = function(...args) { | |
fn.apply(this, args); | |
self.off(el, events, handler); | |
}; | |
this.on(el, events, handler); | |
} | |
off(el, events, fn) { | |
if (typeof el.removeEventListener === 'function' && typeof events === 'string') { | |
console.debug('off', events); | |
events.split(' ').filter(s => s && s.length).map( | |
s => s.toLowerCase() | |
).filter( | |
s => StupidJelly.isSupported(el, s) | |
).forEach(event => el.removeEventListener(event, fn)); | |
} | |
} | |
} | |
export default new StupidJelly(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment