Remove all event listeners with dynamic attachment

  • Thread starter Kenneth Siewers Møller
  • Start date
K

Kenneth Siewers Møller

Hi there

I have a question about dynamic event binding.

I have a class called Fraction in which a number of events are declared.
Some of the events are:
OnNameChanged
OnCostChanged
OnDateChanged

Objects from this class is created and removed dynamically, using a generic
collection inside a singleton class called SourceFractions.
I then have two methods in the SourceFractions class, AddFraction(Fraction
f) and RemoveFraction(Fraction f), and two events OnFractionAdded and
OnFractionRemoved of delegate type FractionEventHandler(object sender,
Fraction f).
When AddFraction is called it invokes the OnFractionAdded event and the same
goes for the other.

In another class I register for these two events, and when the
OnFractionAdded event fires I register for the Fraction events mentioned
above.

private void OnFractionAddedHandler(object sender, Fraction f)
{
f.OnNameChanged += HandleOnNameChanged;
f.OnCostChanged += HandleOnCostChanged;
f.OnDateChanged += HandleOnDateChanged;

.... do stuff ...
}

When the OnFractionRemoved event fires i then unregister with the Fraction
events like above just with -= instead.

This procedure works fine, but seems a bit tedious... I know I have to
dynamically register for the events, but the unregistration is a pain...

Now, I know that there is a delegate method called RemoveAll(Delegate
source, Delegate value), but would this be able to do the trick of
unregistering all the listeners for a particular instance of a class? And
how does it work..?

I guess I could use it in the RemoveFraction method like:

public void RemoveFraction(Fraction f){
this.source_fractions.Remove(f); // The generic class
if(OnFractionRemoved!=null)
OnFractionRemoved(this, f);
FractionEventHandler.RemoveAll(something goes in here... but what?);
}


I really hope some of you could help me in the right direction...

Thanks in advance
Kenneth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top