2016-01-23 68 views
4

我在檢測ember v2.3.0中的按鍵時遇到了問題。我開始用燼,我試着寫簡單的組件,顯示按鍵。但是,我遇到了運行操作問題並帶有參數。 基本上我可以在didRender中使用this.$().on("keypress",function(){ ... });來獲得keyCode,但我認爲在Ember中這不是一個好習慣。有人可以幫助我嗎?請。 :)在Ember.js v2中檢測按鍵+

這裏是我的代碼: 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); 
    } 

    } 
}); 

編輯
我做了這樣的: http://emberjs.jsbin.com/qipeponiqu/1/edit?html,js,output

有人可以檢討它嗎?我想學習最佳實踐。 :)

+0

你可以做'{{action ... parameters ... on =「keypress」}}' – nem035

+0

@nem找到了一個錯誤,但我仍然不知道如何將按鍵事件傳遞給組件的動作。你可以看看它,請:) http://emberjs.jsbin.com/fipiwaqasu/edit?html,js輸出 – Callen

+0

嗨,在你的代碼中你有'setAction =「updateKey」'但似乎沒有做什麼與它? – locks

回答

3

官方Ember.js指南有一個handling events應該是有幫助的部分。

如果你希望你的組件來處理​​你可以做這樣的:

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)); 
    } 
}); 

full Ember Twiddle的休息,但模板是一樣的你。

+0

耶!非常感謝! :)我嘗試了'keyDown'事件,但現在我發現我把它放在代碼中的錯誤位置。 – Callen