Skip to content

Instantly share code, notes, and snippets.

@kitten
Created May 18, 2015 22:51
Show Gist options
  • Save kitten/ffffd2dd30f51cd97e3c to your computer and use it in GitHub Desktop.
Save kitten/ffffd2dd30f51cd97e3c to your computer and use it in GitHub Desktop.
A generic Store class, that utilises Immutable.js
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