views:

31

answers:

1

On the window I bind two keydown events. The condition for triggering a callback function is a certain sequence:

Event #1: ["down", "right", "a"]
Event #2: ["down", "right", "down", "right", "a"]

How can I check if the user pressed the event 2 keys and then cancel the event 1?

Here is the code, focus on the red div and press the keys A, you will see the two events triggering. I need to know how can I check if a more precise one have been triggered...

To check if the sequence is right I compare the sequence with the end of the user input.

+1  A: 

The more precise one, is the one with more keys. Alter your code so it only $(window).kb once, and to register a sequence, one calls another function that will fill an array structure similar to this:

[
 {
    seq:["down", "right", "down", "right", "a"],
    callback: cb1
 },
 {
    seq:["down", "right", "a"],
    callback: cb2
 }
]

the registration function will insert any new element in this array according to it's seq.length, so this array will always be sorted more precise to less precise.

Now your only $(window).kb, will each time loop this array looking for a match, once found, it will call the corresponding callback and stop iterating the array.

aularon
Your hint was helpful. Here is the updated code http://jsfiddle.net/5xGa6/1/ . Seems to be working fine.
BrunoLM
@BrunoLM Thanks for sharing the new code :)
aularon
Np :) I've optimized the code (http://stackoverflow.com/questions/3662633/how-can-i-optimize-this-code) and now this might be the final version http://jsfiddle.net/eQUhr/
BrunoLM