I would like to declare common handler for variety of events, that will basically route events to the JavaScript part of the app. I myself come for JS/AS3 background, where something like this is a relatively simple thing to do. SilverLight and C# look quite stricter though.
The plan is like follows, JS will call a special [ScriptableMember] with a class name to instantiate and method to call, as string arguments. [ScriptableMember] then must contruct an instance of the class and optionally subscribe to the events, that can be fired by that instance. Events to subscribe to, will be exposed in public static struct of some kind. [ScriptableMember] will have to extract event properties from that struct and subscribe with the single event handler to all of them. Common single event handler then should translate C# events to JS ones.
Obviously everything should be generalized and automated in some kind of factory logic.
One big problem to this is that I cannot know beforehand what will be the type of delegate or EventArgs object. And even if I knew it would have been troublesome to create an overload for each and every case. Is there anyway to define a generic event handler in C#?
UPDATE:
Here is a code snippet that deals with described logic:
[ScriptableMember]
public void exec(string compName, string action, ScriptObject scriptObject)
{
String compFQName;
Type compClass;
object comp;
compFQName = "fully.qualified.name." + compName;
compClass = Type.GetType(compFQName);
if (compClass != null) {
comp = Activator.CreateInstance(compClass);
FieldInfo fieldInfo = compClass.GetField("dispatches", BindingFlags.Static | BindingFlags.Public);
object[] dispatches = (object[])fieldInfo.GetValue(comp);
if (dispatches != null) {
foreach (string eventName in dispatches) {
EventInfo eventInfo = compClass.GetEvent(eventName);
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, "OnComponentEvent");
eventInfo.AddEventHandler(comp, handler);
}
}
}
// ...
}
And then there is an event handler that should catch up all the events:
public void OnComponentEvent(object sender, EventArgs args)
{
// do something ...
}
Every event args must be inherited from
EventArgsclass. If you follow this rule, you just can declare your handler likeand subscribe it to any event
EDIT:
Like said O. R. Mapper, if the signature of your handler is incomparable with told above, you can call it from anonimous method that subscribed to your event, for example:
EDIT:
Since the question suggests unusial .NET feature usage, handling would be unusual too. Since YOU subscribe this to everything you must know what events types can occure. Then handle it like this:
EDIT:
To subscribe it try this:
Why your version doesn`t work is a great mistery.