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
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 CenterFile Exchange에서 Subclass Definition에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by