Reputation: 43
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. :)
Here is my code: http://emberjs.jsbin.com/vucenomibo/edit?html,js,output
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);
}
}
});
EDIT
I made it like that:
http://emberjs.jsbin.com/qipeponiqu/1/edit?html,js,output
Can someone review it, please? I want learn best practices. :)
Upvotes: 4
Views: 4925
Reputation: 6577
The official Ember.js guides have a section on handling events that should be helpful.
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));
}
});
See the full Ember Twiddle for the rest, but the template is the same as yours.
Upvotes: 4