This is a general purpose class to build on. It is inspired by the node.js EventEmitter class. See https://nodejs.org/api/events.html.

Methods

Public methods


Method emit()

Usage

EventEmitter$emit(eventName, ...)


Method on()

Usage

EventEmitter$on(eventName, listener)


Method addListener()

Usage

EventEmitter$addListener(eventName, listener)


Method once()

Usage

EventEmitter$once(eventName, listener)


Method listenerCount()

Usage

EventEmitter$listenerCount(eventName)


Method eventNames()

Usage

EventEmitter$eventNames()


Method rawListeners()

Usage

EventEmitter$rawListeners(eventName)


Method listeners()

Usage

EventEmitter$listeners(eventName)


Method clone()

The objects of this class are cloneable with this method.

Usage

EventEmitter$clone(deep = FALSE)

Arguments

deep

Whether to make a deep clone.

Examples

myEmitter <- EventEmitter$new() myEmitter$on("event", function() { message("an event occured!") } ) myEmitter$emit("event")
#> an event occured!
# The listener is still called when "event" fires: myEmitter$emit("event")
#> an event occured!
# A listener can be registered once: myEmitter$once("event", function() { message("this listener is called only once") } ) # This new listener will be removed when called. myEmitter$emit("event")
#> an event occured!
#> this listener is called only once
# There is now only one listener: myEmitter$emit("event")
#> an event occured!
# An error in a listener will throw an error in R. myEmitter$on("event", function(...) stop("An error in a listener")) # Throw an error: if (FALSE) { myEmitter$emit("event")} # You can catch an error with a special "error" event that is # always emitted when an error occured in a listener: myEmitter$on("error", function(e) cat(conditionMessage(e))) myEmitter$emit("event")
#> an event occured!
#> An error in a listener
# As in the node.js class, a "newListener" event is emitted # before each new listener registration. # The "newListener" event passes two arguments to its listener(s): # `eventName` and `listener`. myEmitter <- EventEmitter$new() # Use once here to avoid infinite recursion: myEmitter$once("newListener", function(eventName, listener) { if(eventName == "event") { myEmitter$on("event", function(...) cat("B")) } }) myEmitter$on("event", function(...) cat("A")) myEmitter$emit("event") # BA
#> BA
# The listener attached to the "newListener" event has been # unregistered and is no more called: myEmitter$on("event", function(...) cat("C")) myEmitter$emit("event") # BAC
#> BAC
# Get the number of listeners for an event: myEmitter$listenerCount("event")
#> [1] 3
# Get the event names which have been registered: myEmitter$eventNames()
#> [1] "event"