The API reference of @playcanvas/observer 1.7.1: observable data (Observer and ObserverList), events and undo history, which PCUI components bind to.
The same pages as Markdown, for AI agents: llms-full.txt.
Class
EventHandle manages the binding and unbinding of event listeners. It provides a convenient way to add, remove, and invoke event handlers associated with specific event names. Each EventHandle is linked to an 'owner' object, typically an instance of the Events class, allowing for elegant event management and chaining.
new EventHandle(owner: Events, name: string, fn: HandleEvent)
Creates an instance of EventHandle.
Parameters
owner (Events): Ownername (string): Namefn (HandleEvent): Callback functioncall(events: Events, ...args: any[]): void
Invokes the callback function associated with the event handle. This method directly triggers the event's callback without the event being emitted by the event system.
Parameters
events (Events)args (any[])on(name: string, fn: HandleEvent): EventHandle
Registers a new event listener on the same owner as the EventHandle. This method allows chaining additional event listeners to the owner of this event handle.
Parameters
name (string): Namefn (HandleEvent): Callback functionReturns EventHandle: EventHandle
unbind(): void
Unbinds the event handle from the owner, effectively removing the event listener. After calling this method, the event handle will no longer trigger the callback function when the event is emitted.
Class
Base class for event handling, providing mechanisms to register, emit, and unbind events. This class supports adding event listeners, emitting events with up to 8 arguments, and managing multiple emitters.
Example
// Create an instance of the Events class
const events = new Events();
// Register an event listener
events.on('testEvent', (arg1, arg2) => {
console.log('Event triggered with arguments:', arg1, arg2);
});
// Emit the event
events.emit('testEvent', 'value1', 'value2');
// Unbind the event listener
events.unbind('testEvent');
new Events()
Creates a new Events instance.
get suspendEvents(): boolean
set suspendEvents(value: boolean)
Gets whether events are suspended.
addEmitter(emitter: Events): void
Adds another emitter. Any events fired by this instance will also be fired on the additional emitter.
Parameters
emitter (Events): The emitteremit(name: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any): Events
Emits the specified event, executing all registered listeners for that event with the provided arguments. If events are suspended, the emit operation will be ignored.
Parameters
name (string): The name of the event to emit.arg0 (any, optional): The first argument to pass to the event listeners.arg1 (any, optional): The second argument to pass to the event listeners.arg2 (any, optional): The third argument to pass to the event listeners.arg3 (any, optional): The fourth argument to pass to the event listeners.arg4 (any, optional): The fifth argument to pass to the event listeners.arg5 (any, optional): The sixth argument to pass to the event listeners.arg6 (any, optional): The seventh argument to pass to the event listeners.arg7 (any, optional): The eighth argument to pass to the event listeners.Returns Events: The current instance for chaining.
Example
// Register an event listener
events.on('testEvent', (arg1, arg2) => {
console.log('Event triggered with arguments:', arg1, arg2);
});
// Emit the event
events.emit('testEvent', 'value1', 'value2');
// Emit the event with more arguments
events.emit('testEvent', 'value1', 'value2', 'value3', 'value4');
on(name: string, fn: HandleEvent): EventHandle
Registers an event listener for the specified event name. If the event is emitted, the callback function is executed with up to 8 arguments.
Parameters
name (string): The name of the event to listen for.fn (HandleEvent): The callback function to be executed when the event is emitted.Returns EventHandle: An EventHandle object that can be used to unbind the event listener.
Example
// Register an event listener
events.on('testEvent', (arg1, arg2) => {
console.log('Event triggered with arguments:', arg1, arg2);
});
// Emit the event
events.emit('testEvent', 'value1', 'value2');
once(name: string, fn: HandleEvent): EventHandle
Registers a one-time event listener for the specified event name. The callback function is executed the next time the event is emitted, and then automatically unbound.
Parameters
name (string): The name of the event to listen for.fn (HandleEvent): The callback function to be executed once when the event is emitted.Returns EventHandle: An EventHandle object that can be used to unbind the event listener
before it is triggered.
Example
// Register a one-time event listener
events.once('testEvent', (arg1, arg2) => {
console.log('Event triggered once with arguments:', arg1, arg2);
});
// Emit the event
events.emit('testEvent', 'value1', 'value2'); // The callback will be called and then unbound.
// Emit the event again
events.emit('testEvent', 'value1', 'value2'); // The callback will not be called this time.
removeEmitter(emitter: Events): void
Removes emitter.
Parameters
emitter (Events): The emitterunbind(name?: string, fn?: HandleEvent): Events
Unbinds an event listener for the specified event name. If a callback function is provided, only that specific listener is removed. If no callback is provided, all listeners for the event are removed. If no event name is provided, all listeners for all events are removed.
Parameters
name (string, optional): The name of the event to unbind. If not provided, all events are
unbound.fn (HandleEvent, optional): The specific callback function to remove. If not provided, all
listeners for the event are removed.Returns Events: The current instance for chaining.
Example
// Register an event listener
const callback = (arg1, arg2) => {
console.log('Event triggered with arguments:', arg1, arg2);
};
events.on('testEvent', callback);
// Unbind the specific event listener
events.unbind('testEvent', callback);
// Unbind all listeners for a specific event
events.unbind('testEvent');
// Unbind all listeners for all events
events.unbind();
Class · extends Events
Manages history actions for undo/redo operations. This class keeps track of actions that can be undone and redone, allowing for complex state management in applications such as editors, games, or any interactive applications where state changes need to be reversible.
Example
const history = new History();
// Define an action
const action = {
name: 'draw',
undo: () => { console.log('Undo draw'); },
redo: () => { console.log('Redo draw'); }
};
// Add the action to history
history.add(action);
// Perform undo
history.undo();
// Perform redo
history.redo();
get canRedo(): boolean
set canRedo(value: boolean)
Gets whether we can redo at this time.
get canUndo(): boolean
set canUndo(value: boolean)
Gets whether we can undo at this time.
get currentAction(): HistoryAction
The current history action.
get executing(): number
set executing(value: number)
Gets the number of async actions currently executing.
get lastAction(): HistoryAction
The last action committed to the history.
add(action: HistoryAction): boolean
Adds a new history action to the stack. If the action has a combine flag and matches the current action's name, the redo function of the current action is updated. If actions have been undone before adding this new action, it removes all actions that come after the current action to maintain a consistent history.
Parameters
action (HistoryAction): The action to add.Returns boolean: Returns true if the action is successfully added, false otherwise.
addAndExecute(action: HistoryAction): Promise<void>
Adds a new history action and immediately executes its redo function.
Parameters
action (HistoryAction): The action.Returns Promise<void>: A promise that resolves once the redo function has been executed.
clear(): void
Clears all history actions.
redo(): Promise<void>
Redoes the next history action. This retrieves the next action from the history stack and executes the action's redo function.
Returns Promise<void>: A promise that resolves once the redo function has been executed.
undo(): Promise<void>
Undoes the last history action. This method retrieves the current action from the history stack and executes the action's undo function.
Returns Promise<void>: A promise that resolves once the undo function has been executed.
new History()get suspendEvents(): boolean · set suspendEvents(value: boolean)addEmitter(emitter: Events): voidemit(name: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any): Historyon(name: string, fn: HandleEvent): EventHandleonce(name: string, fn: HandleEvent): EventHandleremoveEmitter(emitter: Events): voidunbind(name?: string, fn?: HandleEvent): HistoryClass · extends Events
The Observer class is used to observe and manage changes to an object. It allows for tracking modifications to nested properties, emitting events on changes, and maintaining state consistency. This is particularly useful in applications where state management and change tracking are critical, such as in data-driven interfaces or collaborative applications.
Example
const data = {
name: 'John',
age: 30,
address: {
city: 'New York',
zip: '10001'
}
};
const observer = new Observer(data);
observer.on('name:set', (newValue, oldValue) => {
console.log(`Name changed from ${oldValue} to ${newValue}`);
});
observer.set('name', 'Jane'); // Logs: Name changed from John to Jane
new Observer<T extends object>(data?: Partial<T>, options?: ObserverOptions<T>)
Creates a new Observer instance.
Parameters
data (Partial<T>, optional): The initial data to observe.options (ObserverOptions<T>, optional): Additional options for the observer.destroy(): void
Destroys the observer instance.
get<P extends string>(path: P, raw: true): any
Parameters
path (P): Path to the value.raw (true): Retrieve the observer object without converting it to JSON.Returns any: The value at the specified path.
get<P extends string>(path: P, raw?: false): P extends Key<T> ? T[P] : any
Parameters
path (P): Path to the value.raw (false, optional): Retrieve the observer object without converting it to JSON.Returns P extends Key<T> ? T[P] : any: The value at the specified path.
has(path: string): boolean
Query whether the object has the specified property.
Parameters
path (string): Path to the value.Returns boolean: Returns true if the value is present and false otherwise.
insert(path: string, value: any, ind?: number, silent?: boolean, remote?: boolean): boolean
Parameters
path (string): Path to the value.value (any): Value to insert.ind (number, optional): Index to insert the value at.silent (boolean, optional, default false): If true, the insert event will not be emitted.remote (boolean, optional, default false): State value passed to the set event used to disable remote event emission.Returns boolean: Returns true if the value was successfully inserted and false otherwise.
json(): T
Returns T: The current state of the object tracked by the observer.
json(target: any): any
Parameters
target (any): The object to JSONify.Returns any: The current state of the object tracked by the observer.
latest(): Observer<T>
Returns the latest observer instance. This is important when dealing with undo / redo where the observer might have been deleted and/or possibly re-created.
Returns Observer<T>: The latest instance of the observer.
move(path: string, indOld: number, indNew: number, silent?: boolean, remote?: boolean): boolean
Parameters
path (string): Path to the value.indOld (number): Index of the value to move.indNew (number): Index to move the value to.silent (boolean, optional, default false): If true, the move event will not be emitted.remote (boolean, optional, default false): State value passed to the set event used to disable remote event emission.Returns boolean: Returns true if the value was successfully moved and false otherwise.
remove(path: string, ind: number, silent?: boolean, remote?: boolean): boolean
Parameters
path (string): Path to the value.ind (number): Index of the value.silent (boolean, optional, default false): If true, the remove event will not be emitted.remote (boolean, optional, default false): State value passed to the set event used to disable remote event emission.Returns boolean: Returns true if the value was successfully removed and false otherwise.
removeValue(path: string, value: any, silent?: boolean, remote?: boolean): boolean
Parameters
path (string): Path to the value.value (any): Value to remove.silent (boolean, optional, default false): If true, the remove event will not be emitted.remote (boolean, optional, default false): State value passed to the set event used to disable remote event emission.Returns boolean: Returns true if the value was successfully removed and false otherwise.
set<P extends string>(path: P, value: P extends Key<T> ? T[P] : any, silent?: boolean, remote?: boolean, force?: boolean): boolean
Parameters
path (P): Path to the property in the object.value (P extends Key<T> ? T[P] : any): Value to set.silent (boolean, optional): If true, the change will not be recorded in history.remote (boolean, optional): State value passed to the set event used to disable remote event emission.force (boolean, optional): If true, the value will be set even if it is the same as the current value.Returns boolean: Returns true if the value was successfully set and false otherwise.
unset(path: string, silent?: boolean, remote?: boolean): boolean
Parameters
path (string): Path to the value.silent (boolean, optional, default false): If true, the change will not be recorded in history.remote (boolean, optional, default false): State value passed to the set event used to disable remote event emission.Returns boolean: Returns true if the value was successfully unset and false otherwise.
get suspendEvents(): boolean · set suspendEvents(value: boolean)addEmitter(emitter: Events): voidemit(name: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any): Observer<T>on(name: string, fn: HandleEvent): EventHandleonce(name: string, fn: HandleEvent): EventHandleremoveEmitter(emitter: Events): voidunbind(name?: string, fn?: HandleEvent): Observer<T>Class · extends Events
The ObserverHistory module provides a mechanism for tracking changes to an Observer object and storing them in a history stack.
new ObserverHistory<T extends object>(args?: object)
Parameters
args (object, optional, default {}): Arguments
get suspendEvents(): boolean · set suspendEvents(value: boolean)addEmitter(emitter: Events): voidemit(name: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any): ObserverHistory<T>on(name: string, fn: HandleEvent): EventHandleonce(name: string, fn: HandleEvent): EventHandleremoveEmitter(emitter: Events): voidunbind(name?: string, fn?: HandleEvent): ObserverHistory<T>Class · extends Events
The ObserverList class is a list of Observer objects.
new ObserverList<T extends unknown>(options?: object)
Parameters
options (object, optional, default {})
options.index (string, optional): Indexoptions.sorted ((arg0: T, arg1: T) => number, optional): Sortedget suspendEvents(): boolean · set suspendEvents(value: boolean)addEmitter(emitter: Events): voidemit(name: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any): ObserverList<T>on(name: string, fn: HandleEvent): EventHandleonce(name: string, fn: HandleEvent): EventHandleremoveEmitter(emitter: Events): voidunbind(name?: string, fn?: HandleEvent): ObserverList<T>Type alias
Callback used by Events and EventHandle functions. Note the callback is limited to 8 arguments.
type HandleEvent = (arg1?: Value, arg2?: Value, arg3?: Value, arg4?: Value, arg5?: Value, arg6?: Value, arg7?: Value, arg8?: Value) => void
Type alias
Represents an action in the history.
type HistoryAction = undefined
Type alias
The ObserverSync class is used to construct an interface for synchronizing changes from Observer to other services.
type ObserverSync = Events & { enabled: boolean; write: (args: Value[]) => void }