本节内容都来自与官网,稍加翻译
Event and Listener Concepts 概念
The Event Model 模型
Events represent changes or actions that occur within objects. For example,
- Modification of class data 修改了类的数据
- Execution of a method 执行了一个方法
- Querying or setting a property value 查询或设置了一个属性值
- Destruction of an object 销毁一个对象
Basically, any activity that you can detect programmatically can generate an event and communicate information to other objects. 所有的活动都能够唤起一个event并且把信息传递给其他的对象
MATLAB® classes define a process that communicates the occurrence of events to other objects that respond to the events. The event model works this way:
MATLAB定义了一个把event发生的信息传递给其他对象的流程,event模型按照以下方式工作
- A handle class declares a name used to represent an event. Name Events 声明一个名称来表示event
- After creating an object of the event-declaring class, attach listener to that object. Control Listener Lifecycle 在创建一个能检测event的类的对象后,附加给它一个listener
- A call to the handle class
notify
method broadcasts a notice of the event to listeners. The class user determines when to trigger the event. Trigger Events 调用notify函数,把event发生的通知广播给各listener,什么时候唤起event由class的使用者决定 - Listeners execute a callback function when notified that the event has occurred. Specifying Listener Callbacks listener在侦测到event发生的信号后调用callback function
- You can bind listeners to the lifecycle of the object that defines the event, or limit listeners to the existence and scope of the listener object. Control Listener Lifecycle 你能够把listener绑定到定义了event的对象的生命周期上,或把listener的声明周期限制为listener object的生命周期
The following diagram illustrates the event model.
Limitations
There are certain limitations to the use of events:
- The event source cannot guarantee that listeners exist when triggering the event. event源不能保证所有listener能够在它被触发时还存在
- A listener cannot prevent other listeners from being notified that the event occurred. 一个listener不能够阻止其他event侦听event的发生
- The order in which listeners execute is not defined. listener执行的顺序没有定义
- Listeners should not modify the event data object passed to the listener callback, because other listeners are passed this same handle object. listener不应该修改传送给callback function的event data,因为其它listener也被传送了相同的handle object
Default Event Data
Events provide information to listener callbacks by passing an event data argument to the callback function. By default, MATLAB passes an event.EventData
object to the listener callback. This object has two properties:
EventName
— The event name as defined in the classevent
blockSource
— The object that is the source of the event
MATLAB passes the source object to the listener callback in the required event data argument. Use the source object to access any of the object’s public properties from within your listener callback function.
Customize Event Data
You can create a subclass of the event.EventData
class to provide additional information to listener callback functions. The subclass would define properties to contain the additional data and provide a method to construct the derived event data object so it can be passed to the notify
method.
Define Event-Specific Data provides an example showing how to customize this data.
Events Only in Handle Classes
You can define events only in handle classes. This restriction exists because a value class is visible only in a single MATLAB workspace so no callback or listener can have access to the object that triggered the event. The callback could have access to a copy of the object. However, accessing a copy is not useful because the callback cannot access the current state of the object that triggered the event or effect any changes in that object.
Comparison of Handle and Value Classes provides general information on handle classes.
Events and Listeners Syntax shows the syntax for defining a handle class and events.
Property-Set and Query Events
There are four predefined events related to properties:
PreSet
— Triggered just before the property value is set, before calling its set access methodPostSet
— Triggered just after the property value is setPreGet
— Triggered just before a property value query is serviced, before calling its get access methodPostGet
— Triggered just after returning the property value to the query
These events are predefined and do not need to be listed in the class events
block.
When a property event occurs, the callback is passed an event.PropertyEvent
object. This object has three properties:
EventName
— The name of the event described by this data objectSource
— The source object whose class defines the event described by the data objectAffectedObject
— The object whose property is the source for this event (that is,AffectedObject
contains the object whose property was either accessed or modified).
You can define your own property-change event data by subclassing the event.EventData
class. The event.PropertyEvent
class is a sealed subclass of event.EventData
.
See Listen for Changes to Property Values for a description of the process for creating property listeners.
See The PostSet Event Listener for an example.
See Property Access Methods for information on methods that control access to property values.
Events and Listeners Syntax 创建方法
Components to Implement
Implementation of events and listeners involves these components: 创建events和listeners包含如下部分:
- Specification of the name of an event in a handle class — Name Events. 命名event
- A function or method to trigger the event when the action occurs — Trigger Events. 唤起event
- Listener objects to execute callback functions in response to the triggered event — Listen to Events. 侦听event
- Default or custom event data that the event passes to the callback functions — Define Event-Specific Data. event data传递给callback function
Name Events
Define an event by declaring an event name inside an events
block. For example, this class creates an event called ToggledState
:
classdef ToggleButton < handle
properties
State = false
end
events %定义event
ToggledState
end
end
注意是handle类
Trigger Events
The OnStateChange
method calls notify
to trigger the ToggledState
event. Pass the handle of the object that is the source of the event and the name of the event to notify
.
classdef ToggleButton < handle
properties
State = false
end
events
ToggledState %定义event
end
methods
function OnStateChange(obj,newState)
if newState ~= obj.State
obj.State = newState;%修改了State属性,唤起ToggledState
notify(obj,'ToggledState');
end
end
end
end
Listen to Events
After the call to notify
triggers an event, MATLAB® broadcasts a message to all listeners that are defined for that event and source object. There are two ways to create listeners: using the handle class addlistener
or listener
method.
在notify触发了event之后,MATLAB把信息传送给所有订阅了这个event的listener
Use addlistener for Persistent Listeners
If you want the listener to persist beyond the normal variable scope, use addlistener
to create it. The event source object holds a reference to the listener object. When the event source object is destroyed, MATLAB destroys the listener.
This code defines a listener for the ToggleState
event: 定义一个event ‘ToggledState’ 的 listener
lh = addlistener(obj,'ToggleState',@RespondToToggle.handleEvnt);
addlistener
has these arguments:
obj
— The object that is the source of the eventToggleState
— The event name passed as achar
vector@RespondToToggle.handleEvnt
— A function handle to the callback function (see the following definition Define Listener).
Use handle.listener to Decouple Listener and Source
Use the listener
method to create listeners when you want to manage the lifecycle of the listener and do not want a coupling between the event source and listener object. MATLAB does not destroy listeners created with listener
when the event source is destroyed. However, your code must keep the listener object handle in scope when creating listeners using listener
. 如果想控制listener的生命周期,不想把listener的生命周期绑定在event source上,使用listener方法,在event source被销毁后,listener不会被销毁
The listener
method requires the same arguments as addlistener
: the event-naming object, the event name, and a function handle to the callback. listener
returns the handle to the listener object. listener使用方法:
lh = listener(obj,'EventName',@callbackFunction)
For example, this code uses the ToggleState
event discussed previously: 范例:
lh = listener(obj,'ToggleState',@RespondToToggle.handleEvnt)
Callback Function
The listener callback function must accept a minimum of two arguments, which MATLAB automatically passes to the callback. Here are the required arguments:
- The source of the event — that is,
obj
in the call toaddlistener
orevent.listener
. - An
event.EventData
object or a subclass ofevent.EventData
, such as theToggleEventData
object described in, Define Event-Specific Data.
Define the callback function to accept the source object and event data arguments.
function callbackFunction(src,evtdata)
...
end
For more information on callback syntax, see Listener Callback Syntax.
Define Listener
The RespondToToggle
class defines objects that listen for the ToggleState
event defined in the ToggleButton
class.
classdef RespondToToggle < handle
methods
function obj = RespondToToggle(toggle_button_obj)
addlistener(toggle_button_obj,'ToggledState',@RespondToToggle.handleEvnt); %给类添加一个listener,能够响应event 'ToggledState'
end
end
methods (Static)
function handleEvnt(src,~) %这时callback function
if src.State
disp('ToggledState is true')
else
disp('ToggledState is false')
end
end
end
end
注意是handle类
The class RespondToToggle
adds the listener in its constructor. In this case, the class defines the callback (handleEvnt
) as a static method that accepts the two required arguments:
src
— The handle of the object triggering the event (that is, aToggleButton
object)evtdata
— Anevent.EventData
object
For example, this code creates objects of both classes:
tb = ToggleButton;
rtt = RespondToToggle(tb);
Whenever you call the OnStateChange
method of the ToggleButton
object, notify
triggers the event. For this example, the callback displays the value of the State
property:
tb.OnStateChange(true)
ToggledState is true
tb.OnStateChange(false)
ToggledState is false
Remove Listeners
Remove a listener object by calling delete
on its handle. For example, if the class RespondToToggle
saved the listener handle as a property, you could delete the listener.
classdef RespondToToggle < handle
properties
ListenerHandle % Property for listener handle
end
methods
function obj = RespondToToggle(toggle_button_obj)
hl = addlistener(toggle_button_obj,'ToggledState',@RespondToToggle.handleEvnt);
obj.ListenerHandle = hl; % Save listener handle
end
end
methods (Static)
function handleEvnt(src,~)
if src.State
disp('ToggledState is true')
else
disp('ToggledState is false')
end
end
end
end
With this code change, you can remove the listener from an instance of the RespondToToggle
class. For example: 当代码改变时,你能够从RespondToToggle
的一个对象中删除listener
tb = ToggleButton; %定义一个触发event的对象
rtt = RespondToToggle(tb); %定义一个侦测了它的对象
The object rtt
is listening for the ToggleState
event triggered by object tb
. To remove the listener, call delete
on the property containing the listener handle.
rtt
侦测了 tb
的 event ToggleState
,如果想删除listener,调用delete
delete(rtt.ListenerHandle)
To deactivate a listener temporarily, see Temporarily Deactivate Listeners.
Define Event-Specific Data
Suppose that you want to pass the state of the toggle button as a result of the event to the listener callback. You can add more data to the default event data by subclassing the event.EventData
class and adding a property to contain this information. Then you can pass this object to the notify
method.
Note
To save and load objects that are subclasses of event.EventData
, such as ToggleEventData
, enable the ConstructOnLoad
class attribute for the subclass.
classdef (ConstructOnLoad) ToggleEventData < event.EventData
properties
NewState
end
methods
function data = ToggleEventData(newState)
data.NewState = newState;
end
end
end
The call to notify
can use the ToggleEventData
constructor to create the necessary argument.
evtdata = ToggleEventData(newState);
notify(obj,'ToggledState',evtdata);