Skip to content

Instantly share code, notes, and snippets.

@jhsu
Created December 8, 2014 22:56
Show Gist options
  • Save jhsu/4c611f42ba7b65339766 to your computer and use it in GitHub Desktop.
Save jhsu/4c611f42ba7b65339766 to your computer and use it in GitHub Desktop.
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