Skip to content
Enact

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 {Component} from 'react';

class MyComponent extends 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} />
    );
  }
}
handle( handlers )  EventHandler

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 Param
handlers...HandlerFunction

List of handlers to process the event.

Returns
EventHandler

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

adaptEvent( adapter, handler )  HandlerFunction

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 Params
adapterEventAdapter

Function to adapt the event payload

handlerHandlerFunction

Handler to call with the handler function

Returns
HandlerFunction

Returns an core/handlecore/handle.HandlerFunction (suitable for passing to handle) that returns the result of handler

call( method )  HandlerFunction

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

If the methods exist 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
methodString

Name of method

Returns
HandlerFunction

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

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', ev)
);
3 Params
propString

Name of property on event

valueAny

Value of property

evObject

Event payload

Returns
Boolean

Returns true if prop on event strictly equals value

forKey( name, ev )  Boolean

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

Example:

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

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

Name from core/keymapcore/keymap

evObject

Event payload

Returns
Boolean

Returns true if event.keyCode is mapped to name

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', ev)
);
2 Params
valueNumber

keyCode to test

evObject

Event payload

Returns
Boolean

Returns true if event.keyCode strictly equals value

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', ev)
);
4 Params
propString

Name of property on props object

valueAny

Value of property

evObject

Event payload

propsObject

Props object

Returns
Boolean

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

forward( name, ev, props )  any

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', ev)
);
3 Params
nameString

Name of method on the props

evObject

Event payload

propsObject

Props object

Returns
any

Always returns true

forwardCustom( name, {adapter} )  HandlerFunction

Creates a handler that will forward the event to a function at name on props.

If adapter is not specified, a new event payload will be generated with a type member with the name of the custom event. If adapter is specified, the type member is added to the value returned by adapter.

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 {forwardCustom} from '@enact/core/handle';

// calls the onChange callback with the event: {type: 'onChange'}
const forwardChange = forwardCustom('onChange');

// calls the onChange callback with the event: {type: 'onChange', index}
const forwardChangeWithIndex = forwardCustom('onChange', (ev, {index}) => ({index}));
2 Params
nameString

Name of method on the props

OptionaladapterEventAdapter

Function to adapt the event payload

Returns
HandlerFunction

Returns an core/handlecore/handle.EventHandler (suitable for passing to handle or used directly within handlers in core/kindcore/kind) that will forward the custom event.

log( message, ev, {args} )  any

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')
);
3 Params
messageString

Custom message

evObject

Event payload

Optionalargs...Any

Any args passed are logged

Returns
any

Always returns true

not( handler )  HandlerFunction

Accepts a handler and returns the logical complement of the value returned from the handler.

Example:

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

// calls the onChange callback when disabled is not true
const handleChange = handle(
 not(forProp('disabled', true)),
 forward('onChange')
)
1 Param
handlerHandlerFunction

Handler to complement

Returns
HandlerFunction

Returns an core/handlecore/handle.HandlerFunction (suitable for passing to handle) that returns the complement of the return value of handler

oneOf( handlers )  HandlerFunction

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 Param
handlers...HandlerFunction[]

List of conditions and handlers to process the event

Returns
HandlerFunction

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

preventDefault( ev )  any

Calls event.preventDefault() and returns true.

Example:

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

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

Event payload

Returns
any

Always returns true

returnsTrue( {handler} )  HandlerFunction

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
const coercedHandler = handle(
  returnsTrue(doesSomething),
  willAlwaysBeCalled
);

// Used to emulate if/else blocks with `oneOf`
const ifElseHandler = oneOf(
	[forKey('enter'), handleEnter],
	[returnsTrue, handleOtherwise]
);
1 Param
OptionalhandlerFunction

Handler function called before returning true.

Returns
HandlerFunction

A function that returns true

stop( ev )  any

Calls event.stopPropagation() and returns true

Example:

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

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

Event payload

Returns
any

Always returns true

stopImmediate( ev )  any

Calls event.stopImmediatePropagation() and returns true

Example:

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

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

Event payload

Returns
any

Always returns true

any

The signature for core/handlecore/handle.adaptEvent parameter adapter

3 Params
eventany
propsObject(string, any)
contextObject(string, any)
Returns
any

The signature for event handlers

1 Param
eventany
Returns

The signature for event handling functions supported by handle and related functions

3 Params
eventany
propsObject(string, any)
contextObject(string, any)
Returns