ES6 SessionStore
This commit is contained in:
parent
6ffe7ef9b2
commit
536724e7c5
3 changed files with 49 additions and 48 deletions
|
@ -6,53 +6,54 @@ import EventEmitter from 'events';
|
|||
* store that listens for actions and updates its state accordingly, informing any
|
||||
* listeners (views) of state changes via the 'update' event.
|
||||
*/
|
||||
function SessionStore() {
|
||||
// Initialise state
|
||||
this._state = {
|
||||
cachedPassword: localStorage.getItem('mx_pass'),
|
||||
};
|
||||
class SessionStore extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
dis.register(this._onAction.bind(this));
|
||||
// Initialise state
|
||||
this._state = {
|
||||
cachedPassword: localStorage.getItem('mx_pass'),
|
||||
};
|
||||
|
||||
dis.register(this._onAction.bind(this));
|
||||
}
|
||||
|
||||
_update() {
|
||||
// Persist state to localStorage
|
||||
if (this._state.cachedPassword) {
|
||||
localStorage.setItem('mx_pass', this._state.cachedPassword);
|
||||
} else {
|
||||
localStorage.removeItem('mx_pass', this._state.cachedPassword);
|
||||
}
|
||||
|
||||
this.emit('update');
|
||||
}
|
||||
|
||||
_setState(newState) {
|
||||
this._state = Object.assign(this._state, newState);
|
||||
this._update();
|
||||
}
|
||||
|
||||
_onAction(payload) {
|
||||
switch (payload.action) {
|
||||
case 'cached_password':
|
||||
this._setState({
|
||||
cachedPassword: payload.cachedPassword,
|
||||
});
|
||||
break;
|
||||
case 'password_changed':
|
||||
this._setState({
|
||||
cachedPassword: null,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
getCachedPassword() {
|
||||
return this._state.cachedPassword;
|
||||
}
|
||||
}
|
||||
|
||||
// Inherit from EventEmitter
|
||||
SessionStore.prototype = EventEmitter.prototype;
|
||||
|
||||
SessionStore.prototype._update = function() {
|
||||
// Persist state to localStorage
|
||||
if (this._state.cachedPassword) {
|
||||
localStorage.setItem('mx_pass', this._state.cachedPassword);
|
||||
} else {
|
||||
localStorage.removeItem('mx_pass', this._state.cachedPassword);
|
||||
}
|
||||
|
||||
this.emit('update');
|
||||
};
|
||||
|
||||
SessionStore.prototype._setState = function(newState) {
|
||||
this._state = Object.assign(this._state, newState);
|
||||
this._update();
|
||||
};
|
||||
|
||||
SessionStore.prototype._onAction = function(payload) {
|
||||
switch (payload.action) {
|
||||
case 'cached_password':
|
||||
this._setState({
|
||||
cachedPassword: payload.cachedPassword,
|
||||
});
|
||||
break;
|
||||
case 'password_changed':
|
||||
this._setState({
|
||||
cachedPassword: null,
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
SessionStore.prototype.getCachedPassword = function() {
|
||||
return this._state.cachedPassword;
|
||||
};
|
||||
|
||||
// Export singleton getter
|
||||
let singletonSessionStore = null;
|
||||
if (!singletonSessionStore) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue