Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle event across chain of objects?

If have the following:

public static void main() { 
    MyClass1 obj = new MyClass1();
    obj.Method1();
}
public class MyClass1() {
    public void Method1() {
        MyClass2 obj = new MyClass2();
        obj.Method1();
    }
}
public class MyClass2() {
   public void Method1() {
       MyClass3 obj = new MyClass3();
       obj.Method1();
   }
}
public class MyClass3() {
   public void Method1() {
       // Raise event here that is handled in MyClass1?    
   }
}

Can MyClass3.Method1() raise an event that is handled in MyClass1?

How would the event handling code be written if I wanted to acheive this?

like image 714
Paul Lassiter Avatar asked Sep 03 '12 07:09

Paul Lassiter


1 Answers

Yes it can, but since each level doesn't know about the deeper levels of you chain, you would have to create events on each class. Some like this:

public static void main() { 
    MyClass1 obj = new MyClass1();
    obj.MyEvent += (s, e) => { Console.WriteLine("Fired!"); };
    obj.Method1();
}

public class MyClass1 {
    public void Method1() {
        MyClass2 obj = new MyClass2();
        obj.MyEvent += (s, e) => { OnMyEvent(); };
        obj.Method1();
    }
    public event EventHandler MyEvent;
    private void OnMyEvent() {
        var myEvent = MyEvent;
        if (myEvent != null)
            myEvent(this, EventArgs.Empty);
    }
}
public class MyClass2 {
    public void Method1() {
        MyClass3 obj = new MyClass3();
        obj.MyEvent += (s, e) => { OnMyEvent(); };
        obj.Method1();
    }
    public event EventHandler MyEvent;
    private void OnMyEvent() {
        var myEvent = MyEvent;
        if (myEvent != null)
            myEvent(this, EventArgs.Empty);
    }
}
public class MyClass3 {
    public void Method1() {
        // Raise event here that is handled in MyClass1?    
        OnMyEvent();
    }
    public event EventHandler MyEvent;
    private void OnMyEvent() {
        var myEvent = MyEvent;
        if (myEvent != null)
            myEvent(this, EventArgs.Empty);
    }
}
like image 134
Maarten Avatar answered Sep 18 '22 07:09

Maarten