Last active
March 14, 2019 00:42
-
-
Save r17x/e7c94697ff2bf868bd06a3f13404abd8 to your computer and use it in GitHub Desktop.
Learning How Object is Work for your Own State Management
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
| /** | |
| * @description Learning How Object is Work for your Own State Management | |
| * @author ri7nz <[email protected]> | |
| * @link {github.com/ri7nz} | |
| * Just For Fun In Javascript 🤟 | |
| */ | |
| class CreateYourOwnState { | |
| #state | |
| #stateNameInWindow | |
| constructor() { | |
| this.#state = {} | |
| // you can access window.__state{randomnumber}__ | |
| this.#stateNameInWindow = `__state${Math.floor(Math.random() * 999)}__` | |
| Object.assign(window, { | |
| [this.#stateNameInWindow]: this.#state | |
| }) | |
| } | |
| setState(obj, callback) { | |
| Object.assign(this.#state, { ...obj }) | |
| typeof callback === 'function' && callback() | |
| } | |
| get stateNameInWindow(){ | |
| return this.#stateNameInWindow | |
| } | |
| get state() { | |
| return this.#state | |
| } | |
| } | |
| const exampleState = new CreateYourOwnState() | |
| // undefined | |
| exampleState.state | |
| // {} | |
| exampleState.setState({ name: 'ri7nz' }) | |
| // undefined | |
| exampleState.state | |
| // {name: "ri7nz"} | |
| exampleState.setState({ name: 'ri7nz666' }) | |
| // undefined | |
| exampleState.setState({ music: 'MathRock' }) | |
| // undefined | |
| exampleState.setState({ | |
| data: [{ hobby: 'Ngaji' }] | |
| }) | |
| // undefined | |
| exampleState.state | |
| // {name: "ri7nz666", music: "MathRock", data: Array(1)} | |
| // data: Array(1) | |
| // . 0: {hobby: "Ngaji"} | |
| // . length: 1 | |
| // __proto__: Array(0) | |
| // music: "MathRock" | |
| // name: "ri7nz666" | |
| // __proto__: Object |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment