Search code examples
javascriptjquery-animatetargetcreatejsmovieclip

CreateJS (Animate CC) get movie instance name on click


I have searched for a solution to this problem, and while I found several old posts, none of them seemed to resolve an issue, and instead found some unique workarounds that fit that particular task. So i was hoping to bring this up again to see if anyone can suggest something more universal.

I have a single function with a switch inside listening to what movie clip was pressed, and depending on the name of the movie clip, certain action is to be taken. Since CreateJS doesnt seem to pick up on movieclip names, I have assigned my own to the individual movieclips, however, how can I easily check which one was clicked? In AS3 it was done easily with e.target.name

here's a snippet of my code:

this.parentMovie.button1.name = "button1";
this.parentMovie.button2.name = "button2";
this.parentMovie.button3.name = "button3";

this.parentMovie.button1.addEventListener("click", onClick.bind(this));
this.parentMovie.button2.addEventListener("click", onClick.bind(this));
this.parentMovie.button3.addEventListener("click", onClick.bind(this));

function onClick(e)
{
    console.log(this.parentMovie.button1.name);    // returns the name of the movieclip just fine, so I know at least that is carried over.

    switch(/* what do I need to put here?? */) // in AS3 it was e.target.name and it worked great.  In JS it returns as null
    {
        case "button1":
            // do something
            break;

        case "button2":
            // do something
            break;

        case "button3":
            // do something
            break;
    }
}

Thank you very much!


Solution

  • The name property is not automatically created (though maybe it should be). Your switch statement should be easy, just use the variable reference instead:

    function onClick(e)
    {
        console.log(this.parentMovie.button1.name);    // returns the name of the movieclip just fine, so I know at least that is carried over.
    
        switch(e.currentTarget) // Use currentTarget since the button might have children
        {
            case this.parentMovie.button1:
                // do something
                break;
    
            case this.parentMovie.button2:
                // do something
                break;
    
            case this.parentMovie.button3:
                // do something
                break;
        }
    }
    

    It should accomplish what you are trying to do.