- Home /
How can I declare a static public delegate in JS?
- I would like to expose a static public delegate in my JS script file. How can I do this?
- How do I add handlers to the delegate?
I'd basically want to be able to do the following (C#) but for JS:
public static Action Handler;
void OnEnable() { Handler += Foo; }
void OnDisable() { Handler -= Foo; }
void Foo() { // Some interesting code... }
Answer by Statement · Mar 27, 2011 at 12:01 PM
I have only come up with a workaround. I am still curious to see if there is any easier way of going about.
JSDelegate.js
class JSDelegate { // Can't use List.<T> - Compile error: // BCE0015: Node 'callable()' has not been correctly processed. // private var callbacks : List.<function()> = new List.<function()>(); // So we have to use an ArrayList instead.
private var callbacks : ArrayList = new ArrayList();
function Add(callback : function())
{
callbacks.Add(callback);
}
function Remove(callback : function())
{
callbacks.Remove(callback);
}
function Invoke()
{
for (var callback : function() in callbacks)
callback();
}
}
Example1.js
static var Handler : JSDelegate = new JSDelegate();
function OnEnable() { Handler.Add(Bar); }
function OnDisable() { Handler.Remove(Bar); }
function Bar() { Debug.Log("Bar called!"); }
Example2.js
function Update()
{
if (Input.GetKeyDown(KeyCode.E))
Example1.Handler.Invoke();
}
Your answer
Follow this Question
Related Questions
Display the speed of a Game Object in MPH 1 Answer
2Dimensional Array? 1 Answer
Quit Menu errors 2 Answers
Problem in changing texture using javascript 0 Answers
How to make a callback function 3 Answers