Learning Observable By Building Observable
Ben Lesh
4.3K31

Subscription objects are a much better design…

Really helpful post, however, I disagree with the upper statement. OO-style in Javascript leads merely to cumbersome and verbose code. We don’t need the prototype system to implement observables. And method chaining can be easily replaced with composition.

Here is a naive but clean and succinct purely functional approach:

const observable = type => target => observe => {
target.addEventListener(type, observe, true);
return f => f(observe, target, type);
};
const unsubscribe = (observe, target, type) =>
target.removeEventListener(type, observe, true);
const complete = (observe, target, type) => {};
const error = (observe, target, type) => {};
const subscribe = observable => observe => observable(observe);
const map = f => observable => observe => {
return subscribe(observable) (x => observe(f(x)));
}
const comp = f => g => x => f(g(x));
const log = prefix => x => console.log(prefix, x);
const observableClick = observable("click") (document);
const clickObserver = map(e => e.screenX + e.screenY) 
(observableClick) (log("clickObserver #1"));
const clickObserver2 = comp(
map(x => x+ "!")) (map(x => x.screenX + x.screenY)
) (observableClick) (log("clickObserver #2"));
clickObserver(unsubscribe);