Skip to content

Instantly share code, notes, and snippets.

@RainerAtSpirit
Forked from gsoltis/rx.firebase.js
Created November 11, 2015 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RainerAtSpirit/ba5ca3a5e9dfd9efe15c to your computer and use it in GitHub Desktop.
Save RainerAtSpirit/ba5ca3a5e9dfd9efe15c to your computer and use it in GitHub Desktop.
Quick Firebase / RxJS binding prototype
(function () {
var makeCallback = function(eventType, observer) {
if (eventType === 'value') {
return function(snap) {
observer.onNext(snap);
};
} else {
return function(snap, prevName) {
// Wrap into an object, since we can only pass one argument through.
observer.onNext({snapshot: snap, prevName: prevName});
}
}
};
Firebase.prototype.__proto__.observe = function(eventType) {
var query = this;
return Rx.Observable.create(function(observer) {
var listener = query.on(eventType, makeCallback(eventType, observer), function(error) {
observer.onError(error);
});
return function() {
query.off(eventType, listener);
}
}).publish().refCount();
};
})();
/**
* Usage:
*
* var source = new Firebase("https://<your firebase>.firebaseio.com").observe('<event type>');
* console.log(source instanceof Rx.Observable);
* source.subscribe(function(changeData) {
* // If event type is 'value', changeData is a DataSnapshot
* // Otherwise, changeData is {snapshot: DataSnapshot, prevName: optional string of previous child location}
* });
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment