如何将监听器设置为MATLAB对象的结构字段

时间:2015-08-13 12:26:30

标签: matlab oop listener

我有一个MATLAB对象,类似于:

classdef myObj < handle

properties (SetObservable)
    % NOTE: we want this to be a struct, as written, its not
    myStruct
end

methods
    function self = myObj(fieldVal)
        self.myStruct = fieldVal;
        % WANT: self.myStruct.myField = fieldVal;

        %  add listener to update if change to self.myStruct
        % WANT: add listener to update if change to
        % self.myStruct.myField
        addlistener(self, 'myStruct', 'PostSet', @self.callbackFnc);
    end

    function callbackFnc(self, varargin)
        fprintf(['self.myStruct is now ', num2str(self.myStruct), '\n'])
    end

end

end

其中有一个实例属性的监听器(乐观地命名为myStruct)。这给出了:

>> tempObj = myObj(3);
>> tempObj.myStruct = 4;
self.myStruct is now 4

如何将侦听器设置为self.myStruct而非self.myStruct字段?

1 个答案:

答案 0 :(得分:1)

你不能直接做你想做的事。您只能将侦听器附加到属性本身,而不是附加到属性的字段(如果属性是结构)。

我会尝试做一些稍微不同的事情,使用set属性的myStruct函数来检测正在设置的字段,然后触发常规事件而不是属性事件:

classdef myObj2 < handle

properties
    myStruct = struct('myField', []);
end

events
    myFieldChanged
end

methods
    function self = myObj2(fieldVal)
        self.myStruct.myField = fieldVal;
        addlistener(self, 'myFieldChanged', @self.callbackFnc);
    end

    function set.myStruct(obj, val)
        oldProp = obj.myStruct;
        obj.myStruct = val;
        if obj.myStruct.myField ~= oldProp.myField
            notify(obj,'myFieldChanged')
        end
    end

    function callbackFnc(self, varargin)
        fprintf(['self.myStruct.myField is now ', num2str(self.myStruct.myField), '\n'])
    end

end

end

希望这个建议有所帮助!