Ember.js:查看按键事件 [英] Ember.js: View listening for keypress event

查看:81
本文介绍了Ember.js:查看按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个包含一些设置信息的面板。该面板通过按钮单击打开/关闭,但我也希望能够通过在键盘上点击 esc 来关闭它。

In my application I have a panel which contains some settings information. This panel is opened/closed with a button click, but I'd also like to be able to close it by hitting esc on the keyboard.

我的View的代码如下所示:

The code for my View looks like this:

Social.MainPanelView = Ember.View.extend({
    elementId: 'panel-account-settings',
    classNames: ['panel', 'closed'],
    keypress: function(e){
        console.log(e);
        console.log('keypress');
    },
    close: function(){
        this.$().prepareTransition().addClass("closed");
    }
});

我尝试过keyup和keydown,但没有任何反应。我怀疑这是因为这不是一个输入类型的View,而只是一个标准的视图。那么如何从一个关键事件触发一个View的方法呢?

I've tried keyup and keydown as well but nothing happens. I suspect that it's because that this isn't an "input" type View but just a standard view. So how can I trigger a method on a View from a key event?

我应该澄清一点,这不是在这个特定元素的路由的上下文中。我打开这个独立的面板,可以在这个视频中看到:

I should clarify that this is not within the context of a Route for this particular element. I'm opening the panel standalone as can be seen in this video:

http: //screencast.com/t/tDlyMud7Yb7e

更新1

这是一个我创建的快速小提琴,以说明我遇到的问题。我可以很容易地触发点击事件触发,但是我正在寻找一个可以检测esc键被按下并在特定视图上触发一个方法的page wide keyup事件。

Here's a quick fiddle that I've created to illustrate the issue I'm having. I can get the click event to trigger quite easily, but I'm looking for a page wide keyup event that will detect the esc key being pressed and trigger a method on a specific View:

推荐答案

要使keyPress工作,您必须将焦点放在视图上。当它是一个输入,它的工作原理,因为你把重点放在它。

For keyPress to work, you have to bring focus to the view. When it is an input, it works because you are bringing focus to it.

这样的东西:

App = Em.Application.create();

App.IndexController = Em.Controller.extend({
  updateKey: function(keyCode) {
    // Do what you gotta do
    this.set('shortcutKey', keyCode);
  },
  shortcutKey: null
});

App.IndexView = Em.View.extend({
  didInsertElement: function() {
    return this.$().attr({ tabindex: 1 }), this.$().focus();
  },

  keyDown: function(e) {

    this.get('controller').send('updateKey', e.keyCode);
  }
});

以下是一个工作示例: http://jsbin.com/ihuzov/1

Here are a working example: http://jsbin.com/ihuzov/1

这篇关于Ember.js:查看按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆