【问题标题】:Take Keyboard Input Into Ember Component将键盘输入带入 Ember 组件
【发布时间】:2014-08-14 18:24:23
【问题描述】:

我在绿色画布内创建了一个带有矩形块的 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);
    }
  }

});

如果有人能帮忙,我已经为此绞尽脑汁好几个小时了。

【问题讨论】:

    标签: javascript jquery ember.js components


    【解决方案1】:

    连接到画布元素的键位有点棘手,因为画布没有获得焦点。因此,您只需连接到窗口(然后再将其销毁)。

    $(window).on('keyup', {self:this}, this.handleKeyUp );
    

    http://emberjs.jsbin.com/miyatoti/2/edit

    【讨论】:

    • 我在哪里放置实际的 if-then 用于映射按键以更改坐标值?并且会像....:document.onkeydown = function() { switch (window.event.keyCode) { case 37: posx--;休息;案例 39:posx++;休息; } };工作吗?
    • 我将组件范围添加为事件的属性,您可以在 handleKeyUp 方法中执行此操作。这是一个小例子。 emberjs.jsbin.com/miyatoti/4/edit
    猜你喜欢
    • 2014-04-21
    • 2011-06-20
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2011-02-10
    相关资源
    最近更新 更多