Created
December 8, 2014 22:56
-
-
Save jhsu/4c611f42ba7b65339766 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
var Rx = require('rx'); | |
// Create draggable element, nothing fancy going on here | |
var box = document.createElement('div'); | |
box.style.width = box.style.height = '100px'; | |
box.style.backgroundColor = 'grey'; | |
box.style.position = 'absolute'; | |
box.innerText = 'Drag me'; | |
document.body.appendChild(box); | |
// [convention] vars that end with a $ are observable | |
var mousemove$ = Rx.Observable.fromEvent(document, 'mousemove'); | |
var mousedown$ = Rx.Observable.fromEvent(box, 'mousedown'); | |
var mouseup$ = Rx.Observable.fromEvent(box, 'mouseup'); | |
// Compose a new observable of mousedrags, it's an abstraction over three other | |
// observables | |
var mousedrag$ = mousedown$ | |
.flatMap(function(e){ // flatMap works well when you need to return another observable | |
e.preventDefault(); | |
var offsetX = e.offsetX; | |
var offsetY = e.offsetY; | |
// Return a new observable that automatically stops once mouseup occurs | |
return mousemove$ | |
.map(function(e) { | |
return { | |
x: e.clientX - offsetX, | |
y: e.clientY - offsetY | |
}; | |
}) | |
.takeUntil(mouseup$); | |
}); | |
var count = 0; | |
mousedrag$ | |
.forEach(function(i){ | |
count++; | |
box.style.top = String(i.y - 1) + 'px'; | |
box.style.left = String(i.x - 1) + 'px'; | |
}); | |
mouseup$ | |
.forEach(function(i){ | |
console.log(count); | |
count = 0; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment