Using a javascript function as a delegate

Jan 16, 2011 at 2:41 AM

I couldn't find an example in the documentation of how to do this, so I was hoping someone could help me out.

Basically, I want to be able to hook this section of javascript code

var event = function(e)
{
 System.Console.Out.WriteLine(e.ToString());

}


 to this event

event MovementFinished movementfinished;
defined by this delegate
public delegate void MovementFinished(MapLayerEventArgs e);

I tried the following:

adding return event; to the bottom of the javascript file, but then i dont know how to assign the returned object to that event.

I can get it to work using the following code:

var times = 0;

var MakeMapEvent = function(map)
{
map.SubscribeMovementFinished(event);
}
var RemoveMapEvent = function(map)
{
map.UnsubscribeMovementFinished(event);
}
var event = function(e)
{
times = times + 1;
System.Console.Out.WriteLine(e.ToString());
}

And then calling MakeMapEvent. The problem is this seems wasteful to make a bunch of functions just to do the adding of the event. Additionally, it throws a null object exception when I call it like follows:

Scripting.GameScriptingEngines.GetJScriptScript(property.Value); <-- property.Value points to the javascript textfile
Scripting.GameScriptingEngines.CallFunction("MakeMapEvent", new object[] {map});  <-- calling this throws an object is null exception

these functions are defined here

 public static object GetJScriptScript(string path)
{
if (File.Exists(path))
{
object myobject = null;
TextReader reader = new StreamReader(path);
var Result = JScriptEngine.Run(reader);
 return Result;
}
return null;
}

public static object CallFunction(string name, object[] parameters)
{
return JScriptEngine.CallFunction(name, parameters);
}

If someone could help me out that'd be great. One more thing I was wondering, is Jint sensitive to lines in the javascript files? because if turn the above javascript code into a single line, I get the following exceptions "no viable alternative at input 'var' at line 1:87 no viable alternative at input 'var' at line 1:163". I ask because I'm using an external program to build map files with xml, and if I use the program to embed the javascript into the xml file, it always gets set on a single line, so this is a bit of a problem.

Any help would be greatly appreciated. Thanks.