Skip to content

Instantly share code, notes, and snippets.

@arturparkhisenko
Created March 17, 2017 18:43
Show Gist options
  • Save arturparkhisenko/397cbf221b19947ee5165e33bc5418f8 to your computer and use it in GitHub Desktop.
Save arturparkhisenko/397cbf221b19947ee5165e33bc5418f8 to your computer and use it in GitHub Desktop.
js-dom-event-listeners
// https://www.webreflection.co.uk/blog/2015/10/22/how-to-add-dom-events-listeners
// arrow function for a click
let click = (evt)=>{evt.preventDefault(); alert('CLICK')}
// arrow function add or remove
node.addEventListener('click', click);
node.removeEventListener('click', click);
// anonymous bound (WeakMap between DOM nodes and objects)
node.addEventListener('click', {
// YES, handleEvent is standard and compatible with
// every browser since about ever!
handleEvent: function (e) {
if (node.getAttribute('last-click')) return this.drop(e);
alert('CLICKER');
},
// removes pretty much any listener through any event
drop: function (e) {
e.currentTarget.removeEventListener(
e.type, this, e.eventPhase === e.CAPTURING_PHASE
);
}
});
// named function expression that removes itself
node.addEventListener('click', function click(e) {
if (someConditionIsFalse) {
return e.currentTarget.removeEventListener(e.type, click);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment