问题
I used to have a jQuery app, that had a 'keydown' event once the document was ready. Basically, anytime a user hit a key, it would match the keycode and do something. Now I ported this app to Ember and life became difficult for 2 reasons:
1) The only time a 'keyDown' event can be registered is when the containing element/View has a focus on it. The only way this can be done with non-input fields is by setting the tabindex value, to achieve this, I do this:
didInsertElement:function(){
this.$().attr("tabindex",0);
this.$().focus(); //bringing focus to the view in order to ensure keyDown event is triggered :)
},
keyDown:function(event){
var keycode = event.which || event.keycode;
switch(keycode){
//perform various events
}
}
2) So the above works like a charm, except, it creates an ugly highlighted focus on the application and whenever the application loses focus, the keyDown events do not trigger. I need to explicitly click around the ApplicationView area (which is not the entire body).
All I really want is to have a simple keydown event triggered the same way it was when I had this in jQuery. Any body got ideas what's up?
回答1:
Ember specifically only catches events that happen within the scope of the ember app, so if you want to catch events external to your app (since your entire page isn't an ember app), and not have to have focus on ember you'll have to create those events outside of the scope of ember.
来源:https://stackoverflow.com/questions/20336308/global-keydown-keypress-events-in-emberjs-without-having-to-set-focus