[英]How do I invoke an event within a static method in MatLab?
我有一个静态类,因此所有方法都是静态的。 由于我试图跟踪操作过程中的位置,因此我试图定期触发事件以更新UI。 我的课看起来类似于以下内容:
classdef foo < handle
events
Update
end
methods(Static)
function bar1()
...
notify([], 'Update', EvtData(val));
end
end
end
问题是,当我运行代码并到达notify([]...
行时,出现以下错误:
未定义的命令/功能“通知”。
我以为这是一个被称为这样的静态方法的事实:
foo.bar1()
如何在MatLab的静态方法中触发/调用事件?
MATLAB OOP中的事件与一个句柄对象相关联,该句柄对象是触发事件的源( notify
)。 您必须先注册一个事件处理程序,否则没有一个对象触发您在监听中感兴趣的事件( addlistener
)。
根据类适合您的应用程序的方式,也许您可以实现Singleton模式 :
classdef MyClass < handle
events
Update
end
%# private constructor
methods (Access = private)
function obj = MyClass()
end
end
methods (Static)
%# restrict instantiation of class to one object
function obj = getInstance()
persistent inst;
if isempty(inst)
inst = MyClass();
end
obj = inst;
end
%# register event listener
function registerListener(f)
persistent lh;
if ~isempty(lh)
delete(lh);
end
lh = addlistener(MyClass.getInstance(), 'Update', f);
end
%# some function that will trigger the event
function func()
notify(MyClass.getInstance(), 'Update')
end
end
end
>> MyClass.func
>> MyClass.registerListener(@(o,e)disp('updated'))
>> MyClass.func
updated
>> MyClass.func
updated
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.