Created
December 26, 2017 00:54
-
-
Save DimitarNestorov/48b69a918288e9098db1aab904a2722a to your computer and use it in GitHub Desktop.
Simplified custom DOMTokenList implementation.
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
const forEach = Array.prototype.forEach; | |
module.exports = class TokenList { | |
constructor(){ | |
this.tokens = {}; | |
this.add.apply(this, arguments); | |
} | |
add(){ | |
const { tokens } = this; | |
forEach.call(arguments, token => { | |
tokens[token] = true; | |
}); | |
return this; | |
} | |
remove(){ | |
const { tokens } = this; | |
forEach.call(arguments, token => { | |
delete tokens[token]; | |
}); | |
return this; | |
} | |
contains(token){ | |
return Boolean(this.tokens[token]); | |
} | |
toggle(token, force){ | |
if(typeof force !== `undefined`){ | |
if(force){ | |
this.add(token); | |
return true; | |
}else{ | |
this.remove(token); | |
return false; | |
} | |
} | |
if(this.contains(token)){ | |
this.remove(token); | |
return false; | |
} | |
this.add(token); | |
return true; | |
} | |
get value(){ | |
return Object.keys(this.tokens).join(` `); | |
} | |
replace(oldToken, newToken){ | |
this.remove(oldToken); | |
this.add(newToken); | |
return this; | |
} | |
item(index){ | |
return Object.keys(this.tokens)[index]; | |
} | |
}; |
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
const TokenList = require(`./TokenList`); | |
module.exports = function MyComponent(props){ | |
const classList = new TokenList(`class-a`); | |
if(condition) classList.add(`class-b`); | |
return <div class={classList.value} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Referring to your ideas, I have written a Classes to use it closer to the HTMLElement.classList.
https://gist.github.com/Mapaler/07b643000e5ef24535a1a860d957ed4d