Created
September 13, 2012 05:16
-
-
Save mattpodwysocki/3712043 to your computer and use it in GitHub Desktop.
RxJS + Require.JS
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
<!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> |
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(['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