Skip to content

Instantly share code, notes, and snippets.

@DimitarNestorov
Created December 26, 2017 00:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DimitarNestorov/48b69a918288e9098db1aab904a2722a to your computer and use it in GitHub Desktop.
Save DimitarNestorov/48b69a918288e9098db1aab904a2722a to your computer and use it in GitHub Desktop.
Simplified custom DOMTokenList implementation.
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];
}
};
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} />;
}
@Mapaler
Copy link

Mapaler commented Aug 4, 2022

Referring to your ideas, I have written a Classes to use it closer to the HTMLElement.classList.
https://gist.github.com/Mapaler/07b643000e5ef24535a1a860d957ed4d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment