把键盘输入到余烬组件

Take Keyboard Input Into Ember Component

本文关键字:余烬 组件 输入 键盘      更新时间:2023-09-26

我在绿色画布中创建了一个矩形块的ember组件。

我遇到的麻烦是添加一个键盘输入命令为a S D W在画布周围移动矩形。这在常规javascript或jquery中很容易做到,但在组件模型中我有点迷路了。任何关于这个函数的帮助都是非常有用的。

链接这里是一个ember javascript bin: http://emberjs.jsbin.com/miyatoti/1/edit

这是我现在的组件代码。

 App.BoxGameComponent = Em.Component.extend({
  tagName:'canvas',
  width: 325,
  height: 280,
  refresh:30,
  attributeBindings:['width', 'height'],
  stars:null,
  on:false,

  build: function(){
    var canvas = this.$()[0],
        ctx = canvas.getContext('2d'),
        shippos = [150, 120],
        height = this.get('height'),
        width = this.get('width');

    this.set('shippos', shippos);   
    this.set('ctx', ctx);
    this.set('on', true);
  }.on('didInsertElement'),
  kill: function(){
    this.set('on', false);
  }.on('willDestroyElement'),
  clear: function () {
    var ctx = this.get('ctx'),
        height = this.get('height'),
        width = this.get('width');
    ctx.fillStyle = 'green';
    ctx.clearRect(0, 0, width, height);
    ctx.beginPath();
    ctx.rect(0, 0, width, height);
    ctx.closePath();
    ctx.fill();
  },
    box: function () {
    var that = this;

    var ctx = this.get('ctx'),
        height = this.get('height'),
        width = this.get('width'),
        shippos = this.get('shippos');
    var posx = shippos[0],
        posy = shippos[1];
    ctx.rect(posx,posy,50,50);
    ctx.stroke();

  },

  game: function(){
    if(this.get('on')){
      this.loop();
    }
  }.observes('on'),
  loop: function () {
    var refreshRate = this.get('refresh');
    this.clear();
    this.box();
    if(this.get('on')){
      Em.run.later(this, this.loop, refreshRate);
    }
  }
});

有谁能帮帮忙吗?我已经绞尽脑汁想了几个小时了

连接画布元素有点棘手,因为画布没有焦点。所以你只需连接到窗口(然后稍后销毁它)。

$(window).on('keyup', {self:this}, this.handleKeyUp );
http://emberjs.jsbin.com/miyatoti/2/edit