keyboard navigation using knockout

2019-08-08 19:56发布

问题:

I have an observable array in my viewmodel which I am binding to a list of div elements using foreach and template binding. How can I navigate through these div elements using keyboard's up and down arrow key.

The way I want is when the user clicks on 1 of the div element that gets the focus and when he presses the down arrow key the next div element gets focus and similarly when he presses the up arrow key the previous div gets focus. I have searched all over the internet but didn't came across a suitable answer. Thanks!!

回答1:

There are a few ways I would imagine doing this...here's one...

Give a 'selectedObject' property to your viewModel and handle the click event per div via knockout. When the event is triggered, you can set the 'selectedObject' to the context passed over. In this click event, $.toggle() the css class via jQuery and set up a handler for the down-arrow event on the new div element (be sure to clear out existing event handlers so not to conflict with the new one).

Click-Binding in knockout: http://knockoutjs.com/documentation/click-binding.html Event Binding in JQuery : http://api.jquery.com/bind/

Provide a fiddle with your attempts of this and I'll try to follow-up.



回答2:

I'd advise handling the keyboard shortcuts in the topmost container of your "component/template" for this particular widget. this lets you handle the up / down in one place, instead of making each li responsible for it's shortcuts.

Additionally in order to make the elements selectable using the mouse and native tab events, look into "roving tab indices".

Looking into the focus binding for knockout helps too.

Edit: found this helpful library as well. https://github.com/bramstein/knockout.selection