zoukankan      html  css  js  c++  java
  • [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().

  • 相关阅读:
    影响cpu性能的因素有哪些?
    linux系统中 SElinux安全子系统
    linux 系统中个人用户主页功能
    理解 Segmentation fault
    VI高级命令集锦
    How to be a Star 怎样成为明星?
    名词解释:DEADBEEF
    Unix还能走多远?
    Awk 实例,第 1 部分
    77年出生的朋友,你们过的还好吗?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6138679.html
Copyright © 2011-2022 走看看