JSFiddle - React, Tailwind, and code Playground
by Bart Kalisz
JavaScript
function Frame(initialState) {
this.events = [];
this.state = Object.assign({}, initialState, { count: 0 });
}
// FRAME SHOULD BE A GLOBAL STATE
Frame.prototype = {
setState: function(nextState) {
this.state = Object.assign(this.state, nextState);
},
getState: function(key) {
if (key) {
return this.state[key];
}
return this.state;
},
addEvent: function(name, callback, run) {
this.events.push({
name: name,
callback: () => {
if (callback.call(this, this.state) === false) {
this.stopEvent(name);
}
},
run: !!run,
});
},
removeEvent: function(name) {
this.stopEvent(name);
this.events = this.events.filter(event => event.name !== name);
},
startEvent: function(name) {
this.events.forEach(event => {
if (event.name === name) {
event.run = true;
}
});
},
stopEvent: function(name) {
this.events.forEach(event => {
if (event.name === name) {
event.run = false;
}
});
},
run: function() {
this.events.forEach(event => {
if (event.run) {
event.callback();
}
});
this.setState({ count: this.state.count + 1 });
},
stop: function() {
this.events.forEach(event => {
event.run = false;
});
}
}
console.clear();
const watcher = (function() {
const frame = new Frame({ index: 0 });
const inc = (state) => {
console.log('index', state.index);
frame.setState({ index: state.index + 1 });
};
const sayHi = (state) => {
if (state.index === 10) {
frame.stopEvent('inc');
console.log('Bye! 😢', frame.state);
return false;
}
if (state.index === 0) {
console.log('Hi! 👋', frame.state);
frame.setState({ saidHi: true });
}
};
const stop = () => {
console.log('Stop!');
frame.stop();
};
frame.addEvent('sayHi', sayHi, true);
frame.addEvent('inc', inc, true);
return {
run: () => frame.run(),
stop,
};
})();
setInterval(watcher.run,...