在Ember.js v2 +中检测按键 [英] Detecting keypress in Ember.js v2+
问题描述
我在ember v2.3.0中检测到按键问题。我是ember的初学者,我尝试编写一个显示按下键的简单组件。但是我在运行动作和参数方面遇到了问题。
基本上,我可以在didRender中使用 this。$()。on( keypress,function(){...});
来获取keyCode,但是我认为这不是Ember的好习惯。有人可以帮我吗?请。 :)
I've problem with detecting keypress in ember v2.3.0. I'm beginer with ember and I try write simple component that display pressed key. But I got problem with run action and take parameters.
Basicly I could use this.$().on("keypress",function(){ ... });
in didRender to get keyCode but I think it's not a good practice in Ember. Could someone help me with this? Please. :)
这是我的代码:
http://emberjs.jsbin.com/vucenomibo/edit?html,js,输出
HTML:
<script type="text/x-handlebars" data-template-name="application">
<h2>Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
{{my-component item=this setAction="smth"}}
</script>
<script type="text/x-handlebars" data-template-name="components/my-component">
<div class="app-body" {{action "smth"}} >
Pressed: {{pressedKeyCode}}
</div>
</script>
JS:
App = Em.Application.create();
App.IndexController = Em.Controller.extend({
actions : {
}
});
App.MyComponentComponent = Em.Component.extend({
didRender: function() {
console.log(this.get('context'));
console.log(this.get('item'));
return this.$().attr({ tabindex: 1 }), this.$().focus();
},
pressedKeyCode: null,
actions:{
smth: function(e) {
console.log('aaa');
this.send('displayKey', String.fromCharCode(e.keyCode));
},
displayKey: function(keyCode) {
this.get('item').set('pressedKeyCode', keyCode);
}
}
});
编辑
我做到了:
http://emberjs.jsbin.com/qipeponiqu/1 / edit?html,js,output
有人可以复习吗?我想学习最佳做法。 :)
Can someone review it, please? I want learn best practices. :)
推荐答案
Ember.js官方指南中有关于处理事件应该会有所帮助。
The official Ember.js guides have a section on handling events that should be helpful.
如果您希望使用组件要处理 keydown
,您可以这样做:
If you want your component to handle keydown
you can do it like this:
import Ember from 'ember';
export default Ember.Component.extend({
didRender: function() {
this.$().attr({ tabindex: 1 });
this.$().focus();
},
shortcutKey: null,
keyDown(event) {
this.set('shortcutKey', String.fromCharCode(event.keyCode));
}
});
请参见余下的完整的Ember Twiddle ,但模板与您的模板相同。
See the full Ember Twiddle for the rest, but the template is the same as yours.
这篇关于在Ember.js v2 +中检测按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!