2016-11-15 7 views
1

MATLABハンドルクラスのプロパティpostSetは非常に便利ですが、ネストされたクラスを別々にトリガーすることができれば幸いです。スクリプト例でネストされたMatlabプロパティリスナー

classdef parentClass < handle 
    properties (SetObservable = true) 
     childClass 
    end 

    methods 
     function this = parentClass() 
      this.childClass = childClass(); 
     end 
    end 
end 

classdef childClass < handle 
    properties (SetObservable = true) 
     value 
    end 

    methods 
     function this = childClass() 
      this.value = 0; 
     end 
    end 
end 

"runTestの"

p = parentClass(); 

addlistener(p.childClass,'value','PostSet',@(o,e)disp('child value set')); 
addlistener(p,'childClass','PostSet',@(o,e)disp('parent value set')); 

p.childClass.value = 1; 

結果が(予想通り)

>> runTest 
child value set 
:例示のための2つのネストされたクラスで最小の例

ハウ版、私は結果は次のようになり、このようなことの両方のレベルでのプロパティの変更を検出するためのエレガントな方法を探しています:これを行うには

>> runTest 
child value set 
parent value set 

答えて

0

一つの方法は、PostSetイベントがデフォルトによってトリガされることを事実を使用することであっても前回の値と現在の値が同じ場合。 parentClassのコンストラクタでは、我々はchildClassPostSetイベントにリスナーを追加し、イベントハンドラはchildClassオブジェクトを再割り当て:あなたはイベントとなるようにこれを実装するより慎重になりたい

classdef parentClass < handle 
    properties (SetObservable = true) 
     childClass 
    end 

    methods 
     function this = parentClass() 
      this.childClass = childClass(); 
      addlistener(this.childClass,'value','PostSet', @this.handlePropEvent); 
     end 
     function handlePropEvent(this, src, event) 
      this.childClass = this.childClass; 
     end 

    end 
end 

注意childClassプロパティに別のオブジェクトが割り当てられている場合、リスナーは適切に処分されます(再割り当てされます)。

実際にはchildClassは、おそらく、興味のあるすべてのプロパティの変更によってトリガーされる独自のイベントタイプを実装する必要があります。parentClassはそのイベントだけをリッスンします。

+0

提案をいただきありがとうございます。私は、あなたの "実践的な"提案が行く方法だと信じています。 –

関連する問題