// begin lesson code
import { fromEvent, partition } from 'rxjs';
import { filter, pluck } from 'rxjs/operators';
const MOVE_SPEED = 20;
let leftPosition = 0;
// elems
const box = document.getElementById('box');
// streams
const click$ = fromEvent(document, 'click');
const xPositionClick$ = click$.pipe(pluck('clientX'));
xPositionClick$.subscribe(xPos => {
/*
* Generally if you have a single if statement in
* you subscribe block, prefer filter instead.
*/
if(xPos < window.innerWidth / 2) {
box.style.left = `${leftPosition -= MOVE_SPEED}px`;
} else {
box.style.left = `${leftPosition += MOVE_SPEED}px`;
}
});
If you found youself doing if/else
it is possible to use partition
operator.
// begin lesson code
import { fromEvent, partition, merge } from 'rxjs';
import { filter, pluck, tap } from 'rxjs/operators';
const MOVE_SPEED = 20;
let leftPosition = 0;
// elems
const box = document.getElementById('box');
// streams
const click$ = fromEvent(document, 'click');
const xPositionClick$ = click$.pipe(pluck('clientX'));
const [ clickLeft$, clickRight$ ] = partition(
xPositionClick$,
xPos => xPos < window.innerWidth / 2
);
const moveLeft = () => {
box.style.left = `${leftPosition -= MOVE_SPEED}px`;
}
const moveRight = () => {
box.style.left = `${leftPosition += MOVE_SPEED}px`;
}
const moveLeft$ = clickLeft$.pipe(tap(moveLeft));
const moveRight$ = clickRight$.pipe(tap(moveRight));
merge(moveLeft$, moveRight$).subscribe()
<iframe src="https://stackblitz.com/edit/rxjs-txzn2d?embed=1&file=index.ts" style="width: 100%; height: 500px"></iframe>
标签:box,Use,conditional,const,MOVE,leftPosition,partition,RxJS,click From: https://www.cnblogs.com/Answer1215/p/16816379.html