Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Created September 13, 2012 05:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/3712043 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/3712043 to your computer and use it in GitHub Desktop.
RxJS + Require.JS
<!DOCTYPE html>
<html>
<head>
<title>RequireJS</title>
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<div id="coordinates">0,0</div>
<div id="delta">0</div>
<ul id="buffer"></ul>
</body>
</html>
require(['rx', 'rx.html', 'rx.binding', 'rx.time'], function (Rx) {
var coords = document.querySelector('#coordinates');
var delta = document.querySelector('#delta');
var buffer = document.querySelector('#buffer');
// One and only one subscription
var mousemove = Rx.Observable.fromEvent(document, 'mousemove').publish().refCount();
// Simple coordinates
var d1 = mousemove.subscribe(function (e) {
coords.innerHTML = e.clientX + ',' + e.clientY;
});
// Calculate deltas
var d2 = mousemove.zip(mousemove.skip(1), function (l, r) {
return { clientX: r.clientX - l.clientX, clientY: r.clientY - l.clientY };
}).subscribe(function (e) {
delta.innerHTML = e.clientX + ',' + e.clientY;
});
// Get a buffer of either half a second or 10, whichever hits first
var d3 = mousemove.bufferWithTimeOrCount(500, 10).subscribe(function (e) {
while(buffer.firstChild) {
buffer.removeChild(buffer.firstChild);
}
var node, elem, i, len;
for(i = 0, len = e.length; i < len; i++) {
elem = e[i];
node = document.createElement('li');
node.innerHTML = elem.clientX + ',' + elem.clientY;
buffer.appendChild(node);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment