I'm writing a class definition that uses listeners to modify an object when certain properties are set. Like so:
classdef MyObject < handle
properties (SetObservable)
orientation = 'h'; % h = horizontal, v = vertical, o = other
length
width
end
methods
% Constructor
function mo = MyObject(o)
mo.orientation = o;
addlistener(mo, 'orientation', 'PreSet', @mo.changeOrientation);
end
% Change Orientation Listener
function changeOrientation(mo, src, evnt)
celldisp(src);
celldisp(evnt);
% I want a way to access newor here
if mo.orientation == 'h' && newor == 'o'
tempw = mo.width
mo.width = mo.length
mo.length = tempw;
end
end
% Setter
function set.orientation(mo, newor)
mo.orientation = newor;
end
end
end
I want to be able to use the variable newor when I set the orientation. How do I pass the new orientation variable to the changeOrientation method?
I want to avoid moving the contents of changeOrientation
into the set.orientation
method because Matlab complains about properties (length and width) potentially not being initialized.
EDIT length is NOT dependent on orientation. I just need to swap length and width when the orientation changes. In other cases, the user should be able to set length or width to any positive value.
You cannot do this as the PreSet listener is just that, a listener. The data passed to the listener callback never makes it way back to the object and modifying its value within your listener has no influence.
The purpose of using a PreSet listener is to get the value of the property before it is changed, but not to modify any values before they are actually assigned.
In the code that you have posted, I would likely just do any validation/modification of orientations within the
set.orientation
method of your class.EDIT
Based on your comment, probably the better way to go about this is to make
length
have a shadow propertylength_
that holds the value the user assigns tolength
. When the user requests the value oflength
it can either return this stored value (if orientation == 'v') or thewidth
(if orientation == 'h')This way you don't have to explicitly update
length
when you change the orientation.As a side note, I would not use
length
as a property as that gets a little confused with the built-in functionlength
.