What I am trying to do:
Imagine in the browser there is an array of divs, the divs are instantiated or deleted per user request.
When left arrow or right arrow keys are pressed, the divs should move left or right.
My current ( poorly crafted ) solution:
Event handling and delegation:
function onDocumentKeyDown( event ){
switch ( event.keyCode ){
case 37: App.objectsView.scrollLeft(); break;
case 39: App.objectsView.scrollRight(); break;
}
}
// add event listener to document
function addEventListeners() {
document.addEventListener( 'keydown', onDocumentKeyDown, false );
}
addEventListeners();
Application container view:
App.objectsView = Ember.ContainerView.create({
childViews: [],
// CRUD stuff
createView: function(){ ... },
deleteView: function(){ ... },
updateView: function(){ ... },
// navigation stuff
scrollRight: function(){
this.scroll('right')
},
scrollLeft: function(){
this.scroll('left')
},
scroll: function( direction ){
this.get('childViews').forEach( function( key ){
var object = key;
object.move( direction );
}, this)
},
});
Application view class ( for completeness, not really that relevant ):
App.ObjectView = Ember.View.extend( Animation, {
...
move: function( param ){ ... }
});
*Note, most of the dom selection and change css attribute logic is brought into the view via an Animation mixin.
As you could see, I really don’t like this implementation because:
-
Each key event is bound to to a specific function in container view, what if I want key 37 to do one thing in some context and something else in another context ( for example where the mouse arrow is )?
-
The onDocumentKeyDown function is added to the document, I can’t exactly say why but it looks jarring to me.
-
ObjectsView has both logic that manages instantiation and event delegation. Is the containerView in Ember even meant to handle navigation logic at all? ( I could separate them into two different functions, but if the events are handled the same way, then they seem to be morally equivalent solutions ).
Are there any commonly used patterns in Ember or just any JS MV* framework that handle key event via some sort of single instance central hub, and then propagate to other parts of the system per application state? And this Ember router concept, does that fit in here somehow?
Thank you!
For handling keyboard events with Ember, we have drawn on the EventManager implementation from Flame.js. Perhaps you can take similar inspiration: https://github.com/flamejs/flame.js/blob/master/mixins/event_manager.js