bgaard
bgaard

Reputation: 142

Automatic change values, in instance of class, by event

I would like to create a class that (for simplicity) adds two numbers as soon as I change an input parameter in an instance of the class. For simplicity I have created this class:

classdef test < handle
    properties (Constant)
        privatNummer = 10;
    end

    properties
        brugerNummer;
        sum;
    end

    methods
        function obj = test()
            obj.sum = method1(obj);
        end

        function obj = method1(obj)
            obj.sum = obj.brugerNummer + obj.privatNummer;
        end
    end
end

How do I get it to automatically update obj.sum when I give it a new value? Currently I have to run obj.method1 every time I want to update obj.sum.

I have tried something like this (but I just can't get it working):

classdef test < handle
    properties (Constant)
        privatNummer = 10;
    end

    properties
        brugerNummer;
        sum;
    end

    methods
        function obj = test()
            notify(obj,'StateChange')
            obj.sum = method1(obj);
            addlistener(obj.brugerNummer,'Ændret nummer',@RespondToToggle.method1);
        end

        function src = method1(src)
            src.sum = src.brugerNummer + src.privatNummer; 
        end
    end
    events
        StateChange
    end
end

Upvotes: 0

Views: 72

Answers (1)

bgaard
bgaard

Reputation: 142

I developed two solutions for the problems. The first relying on Dependent properties, setters and getters; the second relying on listeners and callback-functions.

First Solution:

classdef test
    properties (Constant)
        privatNummer = 10;
    end

    properties
        brugerNummer;
    end
    properties (Dependent)
        sum;
    end

    methods   
        function obj = test()
            % Constructor
        end     

        function value = get.sum(obj)
            value = obj.brugerNummer + obj.privatNummer;
        end
    end
end

Second Solution (this was a real hassle):

classdef test < handle
    properties (Constant)
        privatNummer = 10;
    end

    properties (SetObservable)
        brugerNumber;
    end
    properties
        sum;
    end

    methods
        function obj = test()
            % constructor
            addlistener(obj, 'brugerNumber', 'PostSet',@test.callbackFun);
        end

    end

    methods (Static)
        function callbackFun(~,evnt)
            obj = evnt.AffectedObject;
            obj.sum = obj.brugerNumber + obj.privatNummer;
        end     
    end
end

Upvotes: 1

Related Questions