diff --git a/Readme.md b/Readme.md index ba8c956..1bea449 100644 --- a/Readme.md +++ b/Readme.md @@ -14,7 +14,7 @@ Syntax sugar for events handlers. Kind of like the excellent, [classnames](https ## Usage -This module gives you some special syntax to make your event handlers more declarative and functional. You can create handlers for only certain keypresses, or easily attach multiple handlers to a single event. +This module gives you some special syntax to make your event handlers more declarative and functional. You can create handlers for only certain keypresses, or easily attach multiple handlers to a single event. This example calls `updateText` with every keydown event, but also calls `submit` only when enter is pressed: @@ -32,11 +32,22 @@ You may pass an array, object, or just a plain function, and you may also do any var ev = require('@f/event-handler') function render () { - return + return } ``` This will close the input and submit when `enter` is pressed, it will also update the text on every normal keydown. +If your descriptor is an object, the 'default' key will match every event: + +```js +var ev = require('@f/event-handler') + +function render () { + return +} +``` + +This will submit the input when `enter` is pressed and update the text on every __other__ keydown. ## Return values diff --git a/lib/index.js b/lib/index.js index 0cb7279..bee2fd5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -34,10 +34,15 @@ function match (obj) { return function (e) { var chord = eventKey(e) var fn = obj[chord] + var defaultFn = obj.default if (isFunction(fn)) { return fn(e) } + + if (isFunction(defaultFn)) { + return defaultFn(e) + } } } diff --git a/test/index.js b/test/index.js index 2a049c9..abdbd8e 100644 --- a/test/index.js +++ b/test/index.js @@ -19,6 +19,21 @@ test('should work', function (t) { t.end() }) +test('default handler', function (t) { + var descriptor = { + 'ctrl+shift+enter': function() { + return 'combination' + }, + 'default': function() { + return 'default' + } + } + + t.equal(ev(descriptor)(event('ctrl+shift+enter')), 'combination') + t.equal(ev(descriptor)(event('x')), 'default') + t.end() +}) + /** * Helpers */