Skip to content

Instantly share code, notes, and snippets.

@jdaviderb
Created May 1, 2017 15:10
Show Gist options
  • Save jdaviderb/c74168b5148dcd6e617d36b50887451b to your computer and use it in GitHub Desktop.
Save jdaviderb/c74168b5148dcd6e617d36b50887451b to your computer and use it in GitHub Desktop.
compatibilidad con CommonJS
class GT {
constructor () {
this.state = {}
this.actions = {}
this.stateListeners = {}
}
get register () {
return {
state: (name, data) => {
this.state[name] = data
this.stateListeners[name] = []
this.actions[name] = {}
return this
},
modules: (modules) => {
modules.forEach((module) => {
this.register.state(module.name, module.states)
Object.keys(module.actions).forEach((name) => {
module.actions.gt = this
this.actions[module.name][name] = (data) => module.actions[name](data, this)
})
})
return this
},
states: (states) => {
Object.keys(states).forEach((name) => this.create.state(name, states[name]))
return this
}
}
}
subscribe (name, callback) {
this.stateListeners[name].push(callback)
return this
}
dispatchStateListeners (name, data) {
this.stateListeners[name].forEach((listener) => listener(data))
return this
}
setState (name, data) {
Object.keys(data).forEach((key) => {
this.state[name][key] = data[key]
})
this.dispatchStateListeners(name, this.state[name])
return this
}
removeState (name, property) {
if (property) {
delete this.state[name][property]
} else {
delete this.state[name]
}
return this
}
states (name, property) {
if (property) {
return this.state[name][property]
} else {
return this.state[name]
}
}
actions (state, action) {
if (action) {
return this.actions[state][action]
} else {
return this.actions[state]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment