events: Events

Description Usage Arguments Details Examples

Description

Simple tools for emitting and handling events. on and off are used to register and deregister event handlers, and emit is used to emit an event for registered handlers to handle.

Usage

1
2
3
4
5
6
7
on(event, fn, scoped = TRUE)

off(event, id)

emit(event, ...)

stop_propagation()

Arguments

event

The name of a event, as a string.

fn

A function to be executed in response to a emit.

scoped

Boolean; should this event handler be scoped to the current function body?

id

A handler id, as returned by on. Use this to remove a registered handler with off later.

...

Arguments to be passed to registered event handlers.

Details

These functions interact with a global handler registration – if you need to define separate handler registrations, you can use create_handler_registration to generate your own, and call the relevant on, off and emit events on that object.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# use event system in increment a counter
counter <- 0
foo <- function() {
  on("increment", function() { counter <<- counter + 1})
  emit("increment")
}

# call once -- increment counter to 1
foo()
print(counter)

# call again -- increment counter to 2
foo()
print(counter)

# fire event with no listener -- no increment
emit("increment")
print(counter)

# generate a new handler registration, and fire an
# event on that object
registration <- create_handler_registration()
registration$emit("increment")

# counter is still 2
print(counter)

kevinushey/later documentation built on May 20, 2019, 9:09 a.m.