In the Delphi Spring framework there is an example on how to use TObservable.AddListener() in the \Spring4D\Samples\SpringDemos\Demo.Patterns\Observer folder.

But there is not an example showing how to use TObservable.RemoveListener().

Here I add a listener FEditorMonitor := TEditorMonitor.Create; FEditorMonitor.AddListener(TCurrentTimeEditUpdater.Create(Edit1));

if I try to use the following code to remome Edit1 from the Listeners, Edit1 continues to be notified:

FEditorMonitor.RemoveListener(TCurrentTimeEditUpdater.Create(Edit1));

any idea?

有帮助吗?

解决方案

You should REMOVE the PREVIOUSLY ADDED listener, not create YET ANOTHER NEW listener.

var x: TCurrentTimeEditUpdater;
x := TCurrentTimeEditUpdater.Create(Edit1);

FEditorMonitor.AddListener(x); 

...

FEditorMonitor.RemoveListener(x);
x.Free;
{ optionally } x := nil;

Perhaps your confusion is shown in your idea that you were going "to remome Edit1 from the Listeners". But Edit1 was never and never could be a listener. It just does not have the proper behaviour. What you can add to or remove from listeners collection - is a separate bridging object of some T....Updater class. Not the Edit1 itself.

[Listeners Collections containing(..., Updater1, ...) ] -> [Updater1 for(Edit1)] -> [Edit1]

Your starting code looks to me like

Procedure TMainForm.Button1Click(...);
var NewForm: TMainForm;
begin
    NewForm := TMainForm.Create;
    NewForm.Close;
end;

This would not close the form you already see on the display, more so - it would just leak the memory.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top