Skip to content

Instantly share code, notes, and snippets.

@kitten
Created June 25, 2015 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kitten/7f4ef95ee2041bdbcc35 to your computer and use it in GitHub Desktop.
Save kitten/7f4ef95ee2041bdbcc35 to your computer and use it in GitHub Desktop.
A generic Store factory, that utilises Immutable.js and RxJS
import { EventEmitter } from "events";
import { Observable } from "rx";
import { Map, List } from "immutable";
export default {
createStore(extend) {
const CHANGE_EVENT = "change";
const EventListener = Object.assign({}, EventEmitter.prototype, {
changed() {
this.emit(CHANGE_EVENT);
}
});
return Object.assign({
data: new Map(),
stream: Observable.fromEvent(EventListener, CHANGE_EVENT)
.publish()
.refCount(),
get(id) {
if (id) {
return this.data.get(id);
} else {
return this.data.toList();
}
},
set(key, value) {
this.data = this.data.set(key, value);
EventListener.changed();
},
empty() {
this.data = new Map();
},
count() {
return this.data.size;
},
remove(id) {
const _data = this.data.delete(id);
if (_data.size !== this.data) {
this.data = _data;
EventListener.changed();
}
}
}, extend);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment