neolaser
neolaser

Reputation: 6907

ExtJS listening for global keystrokes with Ext.KeyMap

To polish up an application im developing I am adding keyboard shortcuts for common tasks. I can sue Ext.KeyMap to do this like so...

var map = new Ext.KeyMap("my-element", {
    key: 13, // or Ext.EventObject.ENTER
    fn: myHandler,
    scope: myObject
});

But I want to detect "ss" or "qq" i.e. specific double key strokes of letters. Im not sure how to do this....

My idea is to detect the singular keystroke, add a listener to detect a following key stroke. And to handle the gap between them, set a delayed event that deletes the listener after x amount of time.

Any improvements/suggestions/warnings??

Upvotes: 4

Views: 4467

Answers (3)

Rene Saarsoo
Rene Saarsoo

Reputation: 13917

Something like this:

function defineDoubleKeyMap(element, cfg) {
    var repeated, timer;
    return new Ext.KeyMap(element, {
        key: cfg.key,
        fn: function() {
            if (repeated) {
                // when clicked the second time
                // stop timer and call our callback
                repeated = false;
                clearTimeout(timer);
                cfg.fn.call(cfg.scope);
            }
            else {
                // remember we clicked once, forget after delay
                repeated = true;
                // adjust the delay as needed.
                // current 1 sec is probably too long
                timer = (function(){
                    repeated = false;
                }).defer(1000);
            }
        }
    });
}

defineDoubleKeyMap("my-element", {
    key: Ext.EventObject.ENTER,
    fn: myHandle,
    scope: myObject
});

The probem with this code is that pressing quickly ENTER-DELETE-ENTER will also fire the event as if ENTER-ENTER was pressed. If that's not acceptable, then you have to keep track of all the keypresses - I think you'll have to use Ext.get("my-element").on("keypress") for that.

Upvotes: 0

Vlad Nicula
Vlad Nicula

Reputation: 3706

You don't have to remember all the keys pressed, just the last one. When you think at the double click event, it's similar, but since clicking two times is more popular, it's already implemented for us.

Upvotes: 0

Tommi
Tommi

Reputation: 8608

I'm not sure why you would need an additional listener here. Why not store the previous keystroke in a variable (with the timestamp when the keystroke occurred). Then you could just compare the latest keystroke to the previous keystroke. If they are the same, and the timestamp stored is not too far in the past, that's the double key you're after. If the key codes are not the same, or stored timestamp is too old, just update the stored keycode and timestamp with new values.

Upvotes: 4

Related Questions