core/handle

core/handle provides a set of utilities to support handling events for kind()s and React.Components. The default export, handle(), generates an event handler function from a set of input functions. The input functions either process or filter the event. If an input function returns true, handle() will continue processing the event by calling the next input function in the chain. If it returns false (or any falsy value like null or undefined), the event handling chain stops at that input function.

Example:

import {forKey, forward, handle, preventDefault} from '@enact/core/handle';

// logEnter will contain a function that accepts an event, a props object, and a context object
const logEnter = handle(
  forward('onKeyDown'),  // forwards the event to the function passed in the onKeyDown prop
  forKey('enter'),       // if the event.keyCode maps to the enter key, allows event processing to continue
  preventDefault,        // calls event.preventDefault() to prevent the `keypress` event
  (ev, props) => {       // custom event handler -- in this case, logging some text
    // since it doesn't return `true`, no further input functions would be called after this one
    console.log('The Enter key was pressed down');
  }
).finally(() => {
	 console.log('This will log at the end no matter what happens within the handler above')
});

handle() can also be bound to a component instance which allows it to access the instance props and context. This allows you to write consistent event handlers for components created either with kind() or ES6 classes without worrying about from where the props are sourced.

Handlers can either be bound directly using the native bind() method or using the bindAs() utility method that is appended to the handler.

Example:

import {forKey, forward, handle, preventDefault} from '@enact/core/handle';
import React from 'react';

class MyComponent extends React.Component {
  // bind handle() to the instance
  constructor () {
    super();

    // logEnter will be bound to `this` and set as this.handleKeyDown
    //
    // Equivalent to the following with the advantage of set the function name to be displayed in
    // development tool call stacks
    //
    //   this.handleKeyDown = logEnter.bind(this)
    logEnter.bindAs(this, 'handleKeyDown');
  }

  render () {
    return (
      <div onKeyDown={this.handleKeyDown} />
    );
  }
}
import handle from '@enact/core/handle';

Members

handleFunction

handle(…handlers)Function

Allows generating event handlers by chaining input functions to filter or short-circuit the handling flow. Any input function that returns a falsy value will stop the chain.

The returned handler function has a finally() member that accepts a function and returns a new handler function. The accepted function is called once the original handler completes regardless of the returned value.

1 or more Params
handlers Function

List of handlers to process the event.

Returns
Function

A function that accepts an event which is dispatched to each of the provided handlers.

adaptEventFunction

adaptEvent(adapter, handler, {…args})Object

Adapts an event with adapter before calling handler.

The adapter function receives the same arguments as any handler. The value returned from adapter is passed as the first argument to handler with the remaining arguments kept the same. This is often useful to generate a custom event payload before forwarding on to a callback.

Example:

import {adaptEvent, forward} from '@enact/core/handle';

// calls the onChange callback with an event payload containing a type and value member
const incrementAndChange = adaptEvent(
	(ev, props) => ({
	  type: 'onChange',
	  value: props.value + 1
	}),
	forward('onChange')
)
2 or more Params
adapter Function

Function to adapt the event payload

handler Function

Handler to call with the new event payload

args Any
optional

Additional args passed to both adapter and handler

Returns
Object

New event payload

callFunction

call(method)Boolean

Invokes a method by name on the component to which core/handle.handle is bound.

If the methods exists on the object, it is called with the event, props, and context and its return value is returned.

If the method does not exist or handle isn't bound to an instance, it returns false.

Example:

import {call, handle, forProp} from '@enact/core/handle';

const incrementIfEnabled = handle(
  forProp('disabled', false),
  call('increment')
);

class Counter extends React.Component {
  constructor () {
    super();

    this.handleIncrement = incrementIfEnabled.bind(this);
  }

  render () {
    // ...
  }
}
1 Param
method String

Name of method

Returns
Boolean

Returns the value returned by method, or false if the method does not exist

forEventPropFunction

forEventProp(prop, value, ev)Boolean

Allows handling to continue if the value of prop on the event strictly equals value

Example:

import {forEventProp, handle} from '@enact/core/handle';

const logWhenXEqualsZero = handle(
  forEventProp('x', 0),
  (ev) => console.log('ev.x was equal to zero')
);
3 Params
prop String

Name of property on event

value Any

Value of property

ev Object

Event payload

Returns
Boolean

Returns true if prop on event strictly equals value

forKeyFunction

forKey(name, ev)Boolean

Allows handling to continue if the event's keyCode is mapped to name within core/keymap.

Example:

import {forKey, handle} from '@enact/core/handle';

const logForEnterKey = handle(
  forKey('enter'),
  (ev) => console.log('Enter key pressed down')
);
2 Params
name String

Name from core/keymap

ev Object

Event payload

Returns
Boolean

Returns true if event.keyCode is mapped to name

forKeyCodeFunction

forKeyCode(value, ev)Boolean

Allows event handling to continue if event.keyCode === value.

Example:

import {forKeyCode, handle} from '@enact/core/handle';

const logForEscapeKey = handle(
  forKeyCode(27),
  (ev) => console.log('Escape key pressed down')
);
2 Params
value Number

keyCode to test

ev Object

Event payload

Returns
Boolean

Returns true if event.keyCode strictly equals value

forPropFunction

forProp(prop, value, ev, props)Boolean

Allows handling to continue if the value of prop on the props strictly equals value.

Example:

import {forProp, handle} from '@enact/core/handle';

const logWhenChecked = handle(
  forProp('checked', true),
  (ev) => console.log('checked prop is true')
);
4 Params
prop String

Name of property on props object

value Any

Value of property

ev Object

Event payload

props Object

Props object

Returns
Boolean

true if the value of props[prop] strictly equals value

forwardFunction

forward(name, ev, props)Boolean

Forwards the event to a function at name on props. If the specified prop is undefined or is not a function, it is ignored. The return value of the forwarded function is ignored and true is always returned instead.

Example:

import {forward, handle} from '@enact/core/handle';

const forwardAndLog = handle(
  forward('onClick'),
  (ev) => console.log('event forwarded to onClick from props')
);
3 Params
name String

Name of method on the props

ev Object

Event payload

props Object

Props object

Returns
Boolean

Always returns true

logFunction

log(message, ev, {…args})Boolean

Logs the event, props, and context optionally preceded by a custom message. Will only log in development mode.

Example:

import {forProp, handle, log} from '@enact/core/handle';

const logWhenChecked = handle(
  forProp('checked', true),
  log('checked props is true')
);
2 or more Params
message String

Custom message

ev Object

Event payload

args Any
optional

Any args passed are logged

Returns
Boolean

Always returns true

oneOfFunction

oneOf(…handlers)Function

Calls the first handler whose condition passes. Each branch must be passed as an array with the first element being the condition function and the second being the handler function. The same arguments are passed to both the condition function and the handler function. The value returned from the handler is returned.

Example:

const handler = oneOf(
	[forKey('enter'), handleEnter],
	[forKey('left'), handleLeft],
	[forKey('right'), handleRight]
);
1 or more Params
handlers ArrayFunction

List of conditions and handlers to process the event

Returns
Function

A function that accepts an event which is dispatched to each of the conditions and, if it passes, onto the provided handler.

preventDefaultFunction

preventDefault(ev)Boolean

Calls event.preventDefault() and returns true.

Example:

import {handle, preventDefault} from '@enact/core/handle';

const preventAndLog = handle(
  preventDefault,
  (ev) => console.log('preventDefault called')
);
1 Param
ev Object

Event payload

Returns
Boolean

Always returns true

returnsTrueFunction

returnsTrue({handler})Function

A function that always returns true. Optionally accepts a handler function which is called before returning true.

Example:

// Used to coerce an existing function into a handler change
const coercedHandler = handle(
  returnsTrue(doesSomething),
  willAlwaysBeCalled
);

// Used to emulate if/else blocks with `oneOf`
const ifElseHandler = oneOf(
	[forKey('enter'), handleEnter],
	[returnsTrue, handleOtherwise]
);
0 or more Params
handler Function
optional

Handler function called before returning true.

Returns
Function

A function that returns true

stopFunction

stop(ev)Boolean

Calls event.stopPropagation() and returns true

Example:

import {handle, stop} from '@enact/core/handle';

const stopAndLog = handle(
  stop,
  (ev) => console.log('stopPropagation called')
);
1 Param
ev Object

Event payload

Returns
Boolean

Always returns true

stopImmediateFunction

stopImmediate(ev)Boolean

Calls event.stopImmediatePropagation() and returns true

Example:

import {handle, stopImmediate} from '@enact/core/handle';

const stopImmediateAndLog = handle(
  stopImmediate,
  (ev) => console.log('stopImmediatePropagation called')
);
1 Param
ev Object

Event payload

Returns
Boolean

Always returns true

ArrayBooleanFunctionModuleNumberObjectString