Tuesday, September 16, 2008

Use Event

By S.Luann

Event is a reference to a method or mutiple methods whose prototype is defined by a corresonding delegate.
The reason of using event rather than call a method directly are as follows:

Firstly, at the point of time when you define a control or class, you may not know what to do for something happens, a timer control for example, when it ticks to one o'clock, you don't know what to do. It really depends upon the application which uses this timer. Even though you can also use delegate for this matter, .

Secondly, when something happened, there might be a multitude of places where need to function respondingly. In other words, you need handle a event in multiple places and have multiple methods (event handlers) responding to the event. For this matter, using event is the only option.

The following code snippet uses a timer control.

List 1: Define and use a timer control

public class Timer: Control
{
public event EventHandler Tick;
...
public void DoTick()
{
if(Tick!=null)
{
Tick(this, EventArgs.Empty);
}
}

}


public class Client
{
Timer timer = new Timer();
public client()
{
timer.Tick += new EventHandler(this.OnTick);
timer.Tick += new EventHandler(this.OnTick2);
)

public void Start()
{
timer.DoTick();
}

private void OnTick(object sender, EventArgs e)
{
// do something
}

private void OnTick2(object sender, EventArgs e)
{
// do something more
}

}


List 2 shows the use of a timer control on a web page
A timer user control turns out to be simply rendering the page with javascript code like:

List 2: timer control for web page
setTimeout(function() { Anthem_InvokeControlMethod('ClientID', 'DoTick', [], function() {}, null) }, 'Interval'});


where DoTick is a method can be AJAX called as following:

[Anthem.Method]
public void DoTick()
{
...
}

No comments: