Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active November 23, 2018 13:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/6954510 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/6954510 to your computer and use it in GitHub Desktop.
Exploring FromEventPattern in base RxJS with sample implementations in jQuery, DOM, Dojo and Node.js
Observable.fromEventPattern = function (addHandler, removeHandler) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
observer.onNext(e);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount(); // Ensure only one handler
};
// Using Dojo as an example
require(["dojo/on", "dojo/dom", "dojo/domReady!"], function (on, dom) {
var target = dojo.byId('target');
var source = Rx.Observable.fromEventPattern(
function add (h) {
return on('mousemove', h);
},
function remove (h, signal) {
// passes signal as second argument
signal.remove();
});
var subscription = source.subscribe(function (e) {
console.log(e.clientX);
});
});
// Plain ol DOM
function onLoad() {
var target = document.querySelector('#target');
var source = Rx.Observable.fromEventPattern(
function add (h) {
target.addEventListener('mousemove', h, false);
},
function remove (h, signal) {
target.removeEventListener('mousemove', h, false);
});
var subscription = source.subscribe(function (e) {
console.log(e.clientX);
});
}
window.addEventListener('load', onLoaded, false);
// Using jQuery as an example for events
$(function () {
var target = $('#target');
var source = Rx.Observable.fromEventPattern(
function add (h) {
target.bind('mousemove', h);
},
function remove (h) {
target.unbind('mousemove', h);
});
var subscription = source.subscribe(function (e) {
console.log(e.clientX);
});
});
// Using Node.js event emitters
var Rx = require('rx');
var EventEmitter = require('events').EventEmitter;
var e = new EventEmitter();
var source = Rx.Observable.fromEventPattern(
function add (h) {
target.on('data', h);
},
function remove (h, signal) {
target.off('data', h);
});
var subscription = source.subscribe(function (e) {
console.log(e);
});
// Emit an event
e.emit('data', 'foo');
// => foo
@msqaddura
Copy link

when does the remove function gets called? in all cases they always add

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment