函数式编程
简单的一个拖拽例子
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<title>rxjs实现拖拽</title>
<style>
#drag {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
cursor: pointer;
}
</style>
</head>
<body>
<div id="drag"></div>
<script src="./rx-drag.js"></script>
</body>
</html>
rx-drag.js
const {
fromEvent,
operators: { map, takeUntil, concatAll, withLatestFrom }
} = rxjs;
const target = document.getElementById("drag");
const mouseDown = fromEvent(target, "mousedown");
const mouseMove = fromEvent(document, "mousemove");
const mouseUp = fromEvent(document, "mouseup");
mouseDown
.pipe(
map(e => {
const { left, top } = e.target.getBoundingClientRect();
const clickOffsetX = e.clientX - left;
const clickOffsetY = e.clientY - top;
return {
clickOffsetX,
clickOffsetY
};
}),
map(({ clickOffsetX, clickOffsetY }) => {
return mouseMove.pipe(
takeUntil(mouseUp),
map(moveEvent => ({
x: moveEvent.clientX - clickOffsetX,
y: moveEvent.clientY - clickOffsetY
}))
);
}),
concatAll()
)
.subscribe(({ x, y }) => {
target.style.left = `${x}px`;
target.style.top = `${y}px`;
});