Skip to content

Commit

Permalink
Merge pull request madrobby#96 from treshugart/madrobbyGH-95
Browse files Browse the repository at this point in the history
Detect scope after filter has executed to allow for scope to change during filter execution.
  • Loading branch information
madrobby committed Sep 3, 2013
2 parents 6cb5479 + 2435403 commit df2213b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
8 changes: 5 additions & 3 deletions keymaster.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@
};

// handle keydown event
function dispatch(event, scope){
var key, handler, k, i, modifiersMatch;
function dispatch(event) {
var key, handler, k, i, modifiersMatch, scope;
key = event.keyCode;

if (index(_downKeys, key) == -1) {
Expand All @@ -88,6 +88,8 @@
// abort if no potentially matching shortcuts found
if (!(key in _handlers)) return;

scope = getScope();

// for each potential shortcut
for (i = 0; i < _handlers[key].length; i++) {
handler = _handlers[key][i];
Expand Down Expand Up @@ -256,7 +258,7 @@
};

// set the handlers globally on document
addEvent(document, 'keydown', function(event) { dispatch(event, _scope) }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48
addEvent(document, 'keydown', function(event) { dispatch(event) }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48
addEvent(document, 'keyup', clearModifier);

// reset modifiers to false whenever the window is (re)focused.
Expand Down
40 changes: 38 additions & 2 deletions test/keymaster.html
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ <h1>Keymaster unit tests</h1>
var cntIssues = 0, cntFiles = 0;
key('a', 'issues', function(){ cntIssues++ });
key('a', 'files', function(){ cntFiles++ });

key.setScope('issues');
keydown(65);
keyup(65);
Expand All @@ -301,7 +301,7 @@ <h1>Keymaster unit tests</h1>
keydown(65);
keyup(65);
t.assertEqual(1, cntIssues);

key.setScope('files');
keydown(65);
keyup(65);
Expand Down Expand Up @@ -372,6 +372,42 @@ <h1>Keymaster unit tests</h1>
keydown(65); keyup(65);
t.assertEqual(called, true);
window.key = k;
},

testScopeChangeDuringFilter: function(t) {
var oldFilter = key.filter
, scope1Pressed = 0
, scope2Pressed = 0;

key('a', 'scope1', function() {
++scope1Pressed;
});

key('a', 'scope2', function() {
++scope2Pressed;
});

key.filter = function() {
key.setScope('scope1');
return true;
};

keydown(65);
keyup(65);
t.assertTrue(scope1Pressed === 1);

key.filter = function() {
key.setScope('scope2');
return true;
};

keydown(65);
keyup(65);
t.assertTrue(scope1Pressed === 1);
t.assertTrue(scope2Pressed === 1);

key.filter = oldFilter;
key.setScope();
}
});
</script>
Expand Down

0 comments on commit df2213b

Please sign in to comment.