Let me start with a quote from the Script# Dox (regarding limitations in "Atlas" targeted scripts):
"No support for auto-generated event accessors. Auto-generated event accessors require the existence of a Delegate class with Delegate.Combine/Remove semantics, which are not provided
by ASP.NET AJAX. The workaround is to explicitly implement the 2add/remove accessors for events in your code, rather than have the compiler generate it. "
Basically this is saying there are issues with building events in your classes with Script#. It’s not impossible, but it’s not automatic like it is in Nikhil’s Script# (client-side) framework.
Since I recently had to do this and had to search the Internet for a solution (which there is no answer for), I thought it would be good to document how to do it (for both my reference and for others).
How To Add/Remove Events
That comment about needing to create your own add/remove logic is really simple to handle, but your class needs to derive from Sys.Component (or a class like behavior and control which derive from Sys.Component). The code looks like this (In Script#):
1: // add a handler to an event
2: public void add_MyEvent(EventHandler fn)
4: this.Events.AddHandler("MyEvent", fn);
6: // remove a handler from an event
7: public void remove_MyEvent(EventHandler fn)
9: this.Events.AddHandler("MyEvent", fn);
The reason we need to derive from Sys.Component is that Sys.Component gives us the Events property. Events is the container for all our events. New ones will be dynamically generated within that container. Let’s see a simple property we can build to easily get the event back when we want to invoke it.
1: private EventHandler MyEvent
5: return (EventHandler)this.Events.GetHandler("MyEvent");
All of this is well documented. The hard part is. Now I have the event how do I call it with Script#? You might start looking for invoke or apply syntax (which I did. But the answer is quite simple. The EventHandler is a function/method that you can call directly like this:
1: EventHandler evnt = this.MyEvent;
2: evnt(sender, new EventArgs());
BTW, you can do the same type of thing with delegates... they’re just simp0le functions.
I hope that helps someone...
[I really need to write a fuller post on building Behaviors with Script# (in case you don’t realize Behaviors are the foundation of ASP.NET Ajax Extender Controls).]
| posted on Thursday, May 22, 2008 9:30 AM