jeromeetienne / threex.keyboardstate

three.js extension to keep the current state of the keyboard
http://jeromeetienne.github.io/threex.keyboardstate/examples/basic.html
MIT License
55 stars 30 forks source link

handle window blur #2

Open SebastianNette opened 10 years ago

SebastianNette commented 10 years ago

Issue: keyCodes and modifiers are not flag'd as false when the window loses focus. E.g. changing tabs while a key was pressed, etc.

Suggestion:

THREEx.KeyboardState    = function()
{
    // to store the current state
    this.keyCodes   = {};
    this.modifiers  = {};

    // create callback to bind/unbind keyboard events
    var self    = this;
    this._onKeyDown = function(event){ self._onKeyChange(event, true); };
    this._onKeyUp   = function(event){ self._onKeyChange(event, false);};

    // bind keyEvents
    document.addEventListener("keydown", this._onKeyDown, false);
    document.addEventListener("keyup", this._onKeyUp, false);

    // handle blur
    window.addEventListener("blur", function() {
        for(var prop in self.keyCodes)  self.keyCodes[prop] = false;
        for(var prop in self.modifiers)  self.modifiers[prop] = false;
    }, false);
}
jeromeetienne commented 10 years ago

nice! care to do a pull request with the destructor too ?

SebastianNette commented 10 years ago

It's the first time that I make a pull request, I hope I did it right, haha.