[Angular2] Map keyboards events to Function
The idea is when we tape the arrow keys on the keyboard, we want the ball move accodingly.
const leftArrow$ = Observable.fromEvent(document, 'keydown') .filter(event => event.key === 'ArrowLeft') .mapTo(position => this.increment(position, 'x', 10)); const rightArrow$ = Observable.fromEvent(document, 'keydown') .filter(event => event.key === 'ArrowRight') .mapTo(position => this.decrement(position, 'x', 10)); const upArrow$ = Observable.fromEvent(document, 'keydown') .filter(event => event.key === 'ArrowUp') .mapTo(position => this.increment(position, 'y', 10)); const downArrow$ = Observable.fromEvent(document, 'keydown') .filter(event => event.key === 'ArrowDown') .mapTo(position => this.decrement(position, 'y', 10));
increment(obj, prop, value) { return Object.assign({}, obj, {[prop]: obj[prop] + value}); } decrement(obj, prop, value) { return Object.assign({}, obj, {[prop]: obj[prop] - value}); }
Observable.merge(leftArrow$, rightArrow$, downArrow$, upArrow$) .startWith({ x: 200, y: 200 }) .scan((acc, curr) => curr(acc)) .subscribe( p => this.position = p )
Here, 'curr' is the function return from 'mapTo', the 'acc' will remember the position return from the function.
The initial value of 'acc', is from startWith().