Last active
August 29, 2015 14:16
-
-
Save storkme/a3197dafd48b893dfe93 to your computer and use it in GitHub Desktop.
tidy wrapper for socket.io bindings?
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
/** | |
* Uses `Rx.Observable.using` to provide resource-collected Observable stream that produces values | |
* whenever the websocket receives any of the named events passed in as arguments. | |
* | |
* @param {string[]} events - named events to bind listeners to | |
* @returns {Rx.Observable<Array>} | |
*/ | |
bind(...events) { | |
return Rx.Observable.using(() => { | |
//keep a reference to listener functions so we can remove them later | |
let listenerFns = []; | |
//create our observable... | |
let source = Rx.Observable.create((obs) => { | |
//add a listener function for each event passed in as an argument | |
events.forEach((evt) => { | |
let fn = (...args) => { | |
obs.onNext([evt, args]); | |
}; | |
this.socket.on(evt, fn); | |
listenerFns.push([evt, fn]); | |
}); | |
//ALSO add a listener function for the disconnect event, so we can complete this obs stream | |
listenerFns.push(['disconnect', () => { | |
obs.onCompleted(); | |
}]); | |
}); | |
//our disposer function just kills all of the listeners we bound earlier. | |
source.dispose = () => listenerFns.forEach(([evt, fn]) => this.socket.removeListener(evt, fn)); | |
return source; | |
}, | |
(source) => source); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment