MATLAB Object-Oriented Programming

(Joyce) #1
function anyMethod(obj)
...
notify(obj,'EventName');
end
end
end

Any function or method can trigger the event for a specific instance of the class defining
the event. For example, the triggerEvent method calls notify to trigger the
StateChange event:

classdef MyClass < handle
events
StateChange
end
methods
function triggerEvent(obj)
notify(obj,'StateChange')
end
end
end

Trigger the StateChange event with the triggerEvent method:

obj = MyClass;
obj.triggerEvent

Create Listener


Define a listener using the handle class handle.addlisteneror handle.listener
method. Pass a function handle for the listener callback function using one of these
syntaxes:


  • addlistener(SourceOfEvent,'EventName',@functionName) — for an ordinary
    function.

  • addlistener(SourceOfEvent,'EventName',@Obj.methodName) — for a method
    of Obj.

  • addlistener(SourceOfEvent,'EventName',@ClassName.methodName) — for a
    static method of the class ClassName.
    ListenerObject = addlistener(SourceOfEvent,'EventName',@listenerCallback);


addlistener returns the listener object. The input arguments are:

11 Events — Sending and Responding to Messages

Free download pdf