[Javascript + rxjs] Simple drag and drop with Observables

时间:2022-04-08 23:16:42

Armed with the map and concatAll functions, we can create fairly complex interactions in a simple way. We will use Observable to create a simple drag and drop example with basic DOM elements.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
body, html, div, span, p, button, img, hr{
border: 0;
margin: 0;
padding: 0;
}
</style>
</head>
<body> <div id="parent" style="width: 300px; height: 300px; background: red; position: relative;">
<div id="widget" style="width: 150px; height: 30px; background: blue; position: absolute; left: 150px; top: 150px;">Drag me</div>
</div> <script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.22/rx.all.js"></script>
<script src="drag.js"></script>
</body>
</html>
var Observable = Rx.Observable;

var parent = document.getElementById('parent');
var widget = document.getElementById('widget'); var widgetMouseDown = Observable.fromEvent(widget, 'mousedown');
var parentMouseMove = Observable.fromEvent(parent, 'mousemove');
var parentMouseUp = Observable.fromEvent(parent, 'mouseup'); //.map() will create a tow-d array
//[1,2,3].map(function(num){return [3,4,5];}) -->> [[3,4,5],[3,4,5],[3,4,5]]
var drags = widgetMouseDown
.map(function(e) {
return parentMouseMove.takeUntil(parentMouseUp);
})
.concatAll(); //flat to one-d array. drags.forEach(function( e ) {
widget.style.left = e.clientX + "px";
widget.style.top = e.clientY + "px";
});