Last active
July 27, 2018 12:31
-
-
Save o0101/f181ba76e0c9d054afb810e0524afb66 to your computer and use it in GitHub Desktop.
'classchange' Event - with watchClassChange and addEventListener('classchange', ...)
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
"use strict"; | |
{ | |
const config = {attributes: true}; | |
const observer = new MutationObserver(sendEvent); | |
const listDiff = new WeakMap(); | |
Object.assign(self,{watchClassChange}); | |
function sendEvent(attrChanges) { | |
attrChanges | |
.filter(attrChange => attrChange.attributeName === 'class') | |
.forEach(classChange => classChange.target.dispatchEvent( | |
new CustomEvent('classchange',{ | |
bubbles: true, | |
detail: { changes: getChanges(classChange.target) } | |
}))); | |
} | |
function watchClassChange(...elems) { | |
elems | |
.map(elem => (observer.observe(elem,config), elem)) | |
.forEach(elem => !listDiff.has(elem) ? | |
listDiff.set(elem,{classes:new Set(elem.classList)}) | |
: void 0); | |
} | |
function getChanges(elem) { | |
const current = new Set(elem.classList); | |
const cached = listDiff.get(elem); | |
const previous = cached.classes; | |
cached.classes = current; | |
return { | |
added: new Set([...current].filter(c => !previous.has(c))), | |
removed: new Set([...previous].filter(p => !current.has(p))) | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using (after it is placed in page context):