Search code examples
javascriptjqueryprototypeeventtrigger

js triggering event from prototype from different script


I have a script which holds the prototype of a game. Since we are going to reuse this prototype a lot of times I have this in a separate script.

There also is a second script which instantiates the prototype from the main script. In this script I want to catch a event trigger from the prototype.

prototype

$("#trigger").trigger("noPossibilities");

second script:

$("#trigger").on("noPossibilities", function() {
    console.log("no possibilities triggered");
});

I'm probaly missing out on something since the second script doesn't catch the event. The second script is wrapped in a jQuery document ready function and the prototype one is not. Because when I also wrap the first script (which holds the prototype) the second script doesn't know the prototype.

I've searched the internet and I believe it has something to do with the document ready.

I was trying to dispatch the event from the prototype in js which unfortunately doesn't work because i'm probaly doing something wrong there.

This is that part of the script that should trigger the event:

game.triggerEvent("id", "trigger", "noPossibilities");

game.prototype.triggerEvent = function(idOrClass, elementName, eventName){
    if (idOrClass == "id")
    {
        var element = document.getElementById(elementName);
    }
    else
    {
        var element = document.getElementsByClassName(elementName);
    }

    // Create the event
    var event = new CustomEvent(eventName, { "detail": "js event" });

    // Dispatch/Trigger/Fire the event
    element.dispatchEvent(event);
}

I tried to catch it in the same way as mentioned before:

$("#trigger").on("noPossibilities", function() {
    console.log("no possibilities triggered");
});

Really hope someone can help me out.


Solution

  • I found the solution. The problem was with the order of my code in the second script.

    I instantiate a lot of elements of the game in the prototype. Also the element with id "trigger".

    Before I instantiated the prototype (and the elements of the game) I tried to bind the event "noPossibilities" on the element with id trigger. Since this object wasn't instantiated yet there was nothing to bind so it wasn't working.