Search code examples
javascripthaxe

listen to click event JS


I tried to listen to click event in Haxe/JS:

static function main()
{
    var initHandler:Dynamic = init;        
    Browser.window.onload = initHandler;
}

static private function init()
{
    var clickHandler:Dynamic = learnBtn;    
    Browser.document.getElementById("readMoreBtn").addEventListener("click", clickHandler);
}

static private function learnBtn()
{
}

I'm really need all this?

Why i can't do this (without initHandler and clickHandler):

Browser.window.onload = init;

OR

Browser.document.getElementById("readMoreBtn").addEventListener("click", learnBtn);
  1. The JS file not loaded after all the HTML? I can to define that?

  2. It's not related to this topic but I tried to google and search in Haxe.org but nothing. what it is "untyped" keyword.


Solution

  • Using a Dynamic intermediary variable indirectly solves your problem but you should try understanding the compiler error message.

    What the compiler says:

    If you write:

    function init() {
       // do stuff on window.onload
    }
    
    Browser.window.onload = init;
    

    the compiler will tell you:

    Test.hx:22: characters 68-117 : Void -> Void should be js.html.EventListener
    Test.hx:22: characters 68-117 : Void -> Void should be Dynamic -> Void
    

    What does that mean? It means that your function init(), which has a Void->Void signature, should be js.html.EventListener, which is defined as Dynamic->Void.

    The right code:

    In other words you init() function should have an argument so it should be declared as:

    function init(event:Dynamic) {
       // do stuff on window.onload
    }
    

    Forcing the compiler

    You can tell the compiler to let you write possibly incorrect (but we know valid) code:

    var foo:Dynamic = init;
    Browser.window.onload = foo; // always happy
    
    Browser.window.onload = untyped init; // do not type, please
    
    Browser.window.onload = cast init; // I'm sure I'm right