JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/gh/ionstage/jcore@master/jcore.js"></script>
<div class="switch"></div>
<div class="switch"></div>
<div class="switch"></div>
CSS
.switch {
border: 1px solid #333;
display: inline-block;
height: 48px;
width: 48px;
}
.switch.checked {
background-color: orange;
}
JavaScript
class Switch extends jCore.Component {
constructor(el) {
super(el);
this.isChecked = this.prop(false);
this.el.addEventListener('click', () => this.isChecked(true));
}
onredraw() {
this.redrawBy('isChecked', isChecked => {
this.el.classList[isChecked ? 'add' : 'remove']('checked');
});
}
}
class SwitchRelation extends jCore.Relation {
constructor(switches) {
super();
this.switches = switches;
}
update(changedSwitch) {
if (changedSwitch.isChecked()) {
this.switches.forEach(s => s.isChecked(s === changedSwitch));
}
}
}
const elements = document.querySelectorAll('.switch');
const switches = Array.from(elements).map(el => new Switch(el));
const relation = new SwitchRelation(switches);
switches.forEach(s => s.addRelation(relation));
switches[0].isChecked(true);