notify

Triggers an event of a handle object and runs the listeners attached to it.

Category: Programming > Classes

Syntax

notify(obj, 'EventName')

Fires the event and calls every enabled listener with the source object and event data.

notify(obj, 'EventName', eventData)

Passes a custom event.EventData object to the listeners.

Description

Events let an object announce that something happened without knowing who is interested. A client registers a callback with addlistener(obj, 'EventName', callback); notify then calls it synchronously, in the order the listeners were created, before notify returns.

The callback receives two arguments: the source object and an event data object whose EventName and Source properties identify what fired. Notifying an event that the class does not declare is an error. Disabled or deleted listeners are skipped.

Input arguments

obj
Handle object whose class declares the event.
'EventName'
Name of an event declared in an events block of the class.
eventData
Optional object of a subclass of event.EventData.

Example

A listener reacting to an event

writelines(["classdef Btn < handle", "  events", "    Pressed", "  end", "end"], 'Btn.m');
b = Btn;
L = addlistener(b, 'Pressed', @(src, evt) fprintf('%s fired on a %s\n', evt.EventName, class(src)));
notify(b, 'Pressed')
notify(b, 'Pressed')
Output
Pressed fired on a Btn
Pressed fired on a Btn

The example writes the class file Btn.m to the current folder first; in a project you would keep the class in its own file.

See also

addlistener events handle delete