Created
May 18, 2015 22:51
-
-
Save kitten/ffffd2dd30f51cd97e3c to your computer and use it in GitHub Desktop.
A generic Store class, that utilises Immutable.js
This file contains 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
import { EventEmitter } from "events"; | |
import { Map } from "immutable"; | |
const CHANGE_EVENT = "change"; | |
class Store extends EventEmitter { | |
constructor() { | |
super(); | |
this.data = new Map(); | |
} | |
get(id) { | |
if (id) { | |
return this.data.get(id); | |
} else { | |
return this.data.toList(); | |
} | |
} | |
set(obj) { | |
// Replace the entire data set | |
if (obj instanceof Map) { | |
this.data = obj; | |
this.emitChange(); | |
} | |
} | |
count() { | |
return this.data.size; | |
} | |
remove(id) { | |
const newData = this.data.delete(id); | |
if (this.data !== newData) { | |
this.data = newData; | |
this.emitChange(); | |
} | |
} | |
add(id, element) { | |
this.data = this.data.set(id, element); | |
this.emitChange(); | |
} | |
emitChange() { | |
this.emit(CHANGE_EVENT); | |
} | |
addChangeListener(callback) { | |
this.on(CHANGE_EVENT, callback); | |
} | |
removeChangeListener(callback) { | |
this.removeListener(CHANGE_EVENT, callback); | |
} | |
} | |
export default Store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment