Listen for a change in a subclass property

5 ビュー (過去 30 日間)
Walid
Walid 2015 年 6 月 24 日
編集済み: Guillaume 2015 年 6 月 25 日
I have a main class that includes a subclass. I would like to listen for the change in one of the properties of the subclass from within the main class. I can easily code the listner whithin the subclass however I can't find a way to notify the main class. From the main class when I try to listner for changes in the subclass as a whole nothing seems to happen. I am not sure if events would help me.
  2 件のコメント
Walter Roberson
Walter Roberson 2015 年 6 月 25 日
Guillaume
Guillaume 2015 年 6 月 25 日
編集済み: Guillaume 2015 年 6 月 25 日
It looks like it to me.
Walid, if an answer doesn't work for you, then a) don't accept it and b) say so.
edit: and also, don't call your second class subclass, as it's not a subclass and you're just going to confuse everybody who try to help you. subclass has a very specific meaning in OOP.

サインインしてコメントする。

回答 (1 件)

Mukul Rao
Mukul Rao 2015 年 6 月 25 日
Hi , I am not sure I completely understand the context of the question but I was able to create an example that demonstrates how to,
1. Listen to change in properties of a subclass that are inherited from the superclass.
2. Listen to change in properties of a subclass that are NOT inherited from the superclass.
In both cases, the listeners are defined in the superclass and not the subclass. To test the example, copy the two classes to separate files on your MATLAB path and use the following commands on the prompt:
object = sub_mainclass(1,2)
object.prop1 = 5;
object.prop2 = 7;
Here is the example:
classdef mainclass < handle
%MAINCLASS Summary of this class goes here
% Detailed explanation goes here
properties (SetObservable)
prop1
end
methods
function obj = mainclass(inarg)
obj.prop1 = inarg;
addlistener(obj,'prop1','PostSet',@mainclass.detectcallback);
end
%The function addlistenertosubclass is required unless you intend to use
%mainclass only with sub_mainclass
function addlistenertosubclass(obj,propname)
addlistener(obj,propname,'PostSet',@mainclass.detectcallback2);
end
%Listeners added here
function detectcallback(srv,even)
disp('Detected change in inherited property')
end
function detectcallback2(srv,even)
disp('Detected change in non inherited property')
end
end
end
and the subclass,
classdef sub_mainclass < mainclass
%SUB_MAINCLASS Summary of this class goes here
% Detailed explanation goes here
properties (SetObservable)
prop2
end
methods
function obj = sub_mainclass(prop1,prop2)
%Instantiate from the main class
obj@mainclass(prop1);
%Set property 2
obj.prop2 = prop2;
%Activate the listener in the main class now it is aware of
%prop2
addlistenertosubclass(obj,'prop2');
end
end
end

カテゴリ

Help Center および File ExchangeSubclass Definition についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by