Keypress Detection in Ember.js v2 +

I have a problem with keypress detection in ember v2.3.0. I start with ember and I'm trying to write a simple component that displays the key pressed. But I had a problem with running the action and parameters. Basically I could use this.$().on("keypress",function(){ ... });didRender to get keyCode, but I think this is not a good practice in Ember. Can someone help me with this? You are welcome.:)

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 did it like this: http://emberjs.jsbin.com/qipeponiqu/1/edit?html,js,output

Can someone view it please? I want to learn the best practices. :)

+4
1

Ember.js , .

, keydown, :

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 , , .

+3

Source: https://habr.com/ru/post/1625588/


All Articles