Skip to main content
Inspiring
March 23, 2021
Answered

using a varibale to point to a function (like a delegate in c sharp and javascript (I think)

  • March 23, 2021
  • 2 replies
  • 518 views

I was just curious because I am currently doing Unity tutorial in c sharp at the same time.

We used a variable to hold "clickFunction.bind(this);"

Is that similar to a delegate in c sharp? Basically to use a variable to "point" to a function. That way, you can parse that variable to other functions as a parameter, and also makes code easier to read. I read that was great for checking for events on multiple objects for example. Sorry if this is not really a question for this forum. 

 

 

var clickHandler = clickFunction.bind(this);

this.btn.addEventListener("click", clickHandler);

function clickFunction(event)
{

   // implementation here

}

 

  

    This topic has been closed for replies.
    Correct answer kglad

    yes, using a variable to point to a function is what a c# delegate is and it (a delegate) is employed in animate canvas so you can add and remove listeners that call a function with bind().  ie, the following will fail:

     

    this.btn.addEventListener("click", clickHandler.bind(this));

    this.btn.removeEventListener("click",clickHandler.bind(thiis);  // listener NOT removed

     

    while the following will work:

     

    var clickHandler = clickFunction.bind(this);

    this.btn.addEventListener("click", clickHandler)

    this.btn.removeEventListener("click",clickHandler);  // listener removed

    2 replies

    kglad
    Community Expert
    kgladCommunity ExpertCorrect answer
    Community Expert
    March 23, 2021

    yes, using a variable to point to a function is what a c# delegate is and it (a delegate) is employed in animate canvas so you can add and remove listeners that call a function with bind().  ie, the following will fail:

     

    this.btn.addEventListener("click", clickHandler.bind(this));

    this.btn.removeEventListener("click",clickHandler.bind(thiis);  // listener NOT removed

     

    while the following will work:

     

    var clickHandler = clickFunction.bind(this);

    this.btn.addEventListener("click", clickHandler)

    this.btn.removeEventListener("click",clickHandler);  // listener removed

    Inspiring
    March 23, 2021

    Hey guys, that was great. Thanks. I was so curious.

    kglad
    Community Expert
    Community Expert
    March 23, 2021

    you're welcome.

    Legend
    March 23, 2021

    You shouldn't get too hung up on trying to think of one language's features in terms of another's language's features.

     

    All you need to know is that functions in Javascript are first-class objects. That means that references to them can be passed around, assigned, created, and destroyed like every other data type in the language.

     

    https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function