Basic implementation of events and listeners.

3 次查看(过去 30 天)
I am trying to write a class with all properties depending on eachother It seems events and listeners can be used for this, but I can't get the basic implementation of these to work.
% when property a or b is altered, sum will automatically be recalculated
classdef myclass < handle
properties
a = 1;
b = 2;
sum
end
events
valuechange
end
methods
function obj = myclass()
addlistener(obj, valuechange, calc_sum(obj))
end
function obj = set.a(obj, input)
obj.a = input;
notify(obj, valuechange)
end
function obj = set.b(obj, input)
obj.b = input;
notify(obj, valuechange)
end
function calc_sum(obj)
obj.sum = obj.a + obj.b
end
end
end
an attempt to create an object returns following error:
Undefined function or variable 'valuechange'.
Error in myclass (line 18)
addlistener(obj, valuechange, calc_sum(obj))
What am I not understanding?
Thanks

采纳的回答

Daniel Shub
Daniel Shub 2012-10-4
You have three minor problems and one major problem. In the addlistener and notify calls you need to make valuechange into a string 'valuechange'. You also need the callback in addlistener to be a function handle that takes two arguments:
addlistener(obj, 'valuechange', @(obj, evt)calc_sum(obj));
The major problem is that this is not the correct way to do what you are trying to do. The calc_sum callback will only be initiated when the event queue is flushed. This means that there is a period of time in which the class is in an intermediate state (i.e., obj.a+obj.b will not equal obj.sum). You should look into dependent properties. You could also have set.a and set.b call calc_sum directly.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by