Created
June 25, 2015 22:58
-
-
Save kitten/7f4ef95ee2041bdbcc35 to your computer and use it in GitHub Desktop.
A generic Store factory, that utilises Immutable.js and RxJS
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 { 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