-
-
Save ympbyc/4328623 to your computer and use it in GitHub Desktop.
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
require('allthemagicalstuff'); | |
//event object constructor; | |
function event (target, eventName) { | |
return { | |
target: target | |
, eventName: eventName | |
}; | |
}; | |
/* | |
* SIGNALS | |
*/ | |
var MouseE , mouseS; | |
MouseE.clicks = event(document, 'click'); | |
MouseS.position = function (e) { | |
return sigReturn({x:e.pageX, y:pageY}); | |
}; | |
//compound signal | |
function sampleOn (ev, signal) { | |
var samples = []; | |
var signal = extend(function () { | |
return sigReturn(samples); | |
}, EventEmitter); | |
//under the hood we use eventemitter | |
ev.target.addEventListener(ev.eventName, function (e) { | |
samples.push(signal(e)); | |
signal.fire('change'); | |
}); | |
return signal; | |
} | |
//signal monad | |
//make user inaccessible to the raw signal out side | |
function sigReturn (signal) { | |
return { | |
'>>=': function (f) { return f(signal) } | |
} | |
} | |
var clickLocations = sampleOn(MouseE.clicks, MouseS.position); //is a compound signal | |
//capture the scene | |
function scene (locs) { | |
return sigReturn(map(drawPoint, locs)); | |
}; | |
function drawPoint (pt) { | |
pt['>>='](function (p) { | |
canvas.point(p.x, p.y); //side effect | |
}); | |
retrun pt; | |
}; | |
function lift (f, sig) { | |
sig.addEventListener('change', function () { | |
sig()['>>='](f); | |
}); | |
} | |
clickLocations()['>>='](scene); | |
lift(scene, clickLocations); | |
/* | |
* Helpers | |
*/ | |
function extend (dst, src) { | |
var k; | |
for (k in src) | |
if (src.hasOwnProperty(k)) | |
dst[k] = src[k]; | |
return dst; | |
} | |
var EventEmitter = { | |
listeners: [] | |
, addEventListener: function (ev, f) { | |
this.listeners.push({ev:ev, f:f}); | |
}; | |
, fire: function (ev, o) { | |
this.listeners | |
.filter(function (x) {return x.ev === ev}) | |
.forEach(function (l) { | |
l.f(o); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
signalはモナドかなにかでピュアな関数から隔離して閉じ込めたい