How To listen to a list of properties and call a method when a property of that list changes value?
3 views (last 30 days)
Show older comments
Laurent Davenne
on 23 Jan 2018
Commented: Laurent Davenne
on 25 Jan 2018
Hi,
I would like to automatically call a method when some class properties do change.
I have been able to do it for in single property:
mySetup.rwConfigChangeListener = event.proplistener(mySetup,{'rwConfig'},'PostSet', @mySetup.ResetRwAoaToMin);
But now I need a method to be called anytime one of 50 prop do change.
Documentation seems to indicate I should be able to input a list of properties, but I have not been able to do so:
lh = event.proplistener(Hobj,Properties,'PropEvent',@CallbackFunction) creates a property listener object for one or more properties on the specified object.
Hobj — handle of object whose property or properties are to be listened to. If Hobj is an array, the listener responds to the named event on all objects in the array.
Properties — an object array or a cell array of meta.property object handles representing the properties to which you want to listen.
PropEvent — must be one of the strings: PreSet, PostSet, PreGet, PostGet
@CallbackFunction — function handle to the callback function that executes when the event occurs.
Also maybe I should use a different kind of listener?
Thanks for your help.
0 Comments
Accepted Answer
Sean de Wolski
on 23 Jan 2018
You have to build the meta property list from the metaclass:
p = IHaveProps;
mc = metaclass(p);
metaprops = [mc(:).Properties];
listener = event.proplistener(p, metaprops, 'PostSet', @(~,evt)disp(evt))
p.Property1 = pi
p.Property2 = exp(1)
For the class:
classdef IHaveProps < handle
properties (SetObservable)
Property1
Property2
PropertyTuesday
end
end
9 Comments
Guillaume
on 25 Jan 2018
@(~,evt)mySetup.CallBackFunction(mySetup)
This is a very odd construct, the second mySetup is redundant, note that the above is equivalent (ignoring the way matlab search for functions) to:
@(~, evt) CallBackFunction(mySetup, mySetup)
As you can see you're passing the same argument twice. Since you've defined the CallBackFunction as
function CallBackFunction(obj,~,~)
the second mySetup is ignored.
The two way you could define the callback would be
@mySetup.CallbackFunction %preferred
@(~, ~) mySetup.CallbackFunction
Now for some explanation about Sean's callback. An event callback function always receive two inputs: The source generating the event, and some event specific arguments. This is actually fairly standard across many languages. Therefore when Sean defined:
@(~, evt) ...
He defined a function with two inputs as required. That function ignores the first input (the source) and uses the event arguments, which he displays.
More Answers (0)
See Also
Categories
Find more on Historical Contests in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!