I have a class that is meant to be static, and therefore all methods are static. Since I'm trying to keep track of where the process is during an operation, I'm trying to fire an event periodically to update the UI. My class looks something similar to the following:
classdef foo < handle
events
Update
end
methods(Static)
function bar1()
...
notify([], 'Update', EvtData(val));
end
end
end
The problem is that when I run the code, and get to the notify([]...
line, I get the following error:
Undefined command/function 'notify'.
I'm assuming that this has something to be done with the fact that this is a static method being called as such:
foo.bar1()
How do I fire/invoke an event within a static method in MatLab?
Events in MATLAB OOP are associated with a handle object that is the source of the triggered event ( notify
). You cannot register an event handler without having an object that triggers the event you are interesting in listening to ( addlistener
).
Depending on how the class fits in your application, perhaps in your case you can implement the Singleton pattern :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.