Events class provides a simple event emitter implementation for listening to and triggering custom events throughout your plugin.
Overview
TheEvents class allows you to implement the observer pattern, where different parts of your plugin can communicate through events without tight coupling. This is the base class for many Obsidian API classes that need to emit events.
Constructor
Methods
on
Register an event handler callback.The name of the event to listen for
The callback function to execute when the event is triggered. Receives any data passed during
trigger()Optional context (
this binding) for the callback functionA reference to the event registration that can be used with
offref() or Component.registerEvent()Example
off
Unregister an event handler by name and callback.The name of the event to stop listening for
The exact callback function that was registered
Example
offref
Unregister an event handler using an EventRef.The EventRef returned by
on() when the event was registeredExample
trigger
Trigger an event and call all registered handlers.The name of the event to trigger
Any number of arguments to pass to the event handlers
Example
tryTrigger
Attempt to trigger a specific event reference.The event reference to trigger
Array of arguments to pass to the event handler
Best Practices
Use Component.registerEvent()
When working within a Component or Plugin, always useregisterEvent() to automatically clean up event listeners when the component unloads:
Custom Event Classes
Extend the Events class to create custom event emitters:See Also
- Component - For component lifecycle management
- Plugin - For plugin-specific event handling
- Workspace Events - For workspace-related events