x


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...
}
more ▼

asked Mar 26 '11 at 12:22 PM

Statement gravatar image

Statement ♦♦
20.2k 35 71 176

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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();
}
more ▼

answered Mar 27 '11 at 12:01 PM

Statement gravatar image

Statement ♦♦
20.2k 35 71 176

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x110
x31

asked: Mar 26 '11 at 12:22 PM

Seen: 1361 times

Last Updated: Mar 27 '11 at 11:39 AM