Jump to content

JavaScript keydown addEventListener will not call my Class method


IamThatGuy
 Share

Recommended Posts

So I converted this little puzzle block game code I had into a class. Everything seems to be working but one things, which is like the most important thing. It seems like it will not fire the eventListener.

 

 

For some reason, I can't copy and paist anything at all into this forum's textbox, so I can't post snipplets of certain area's as I would like to and that's just way to muchhhh typing for me.

 

WIP: www.orpgcreator.com/3blocks/newBlock.html

 

 

Before I turned my code into a class this worked:

window.addEventListener("keydown", moveBlock);

 

 

So after I initialize my class, I have this line:

 

window.addEventListener("keydown", Player1.moveBlock);

 

I have also stuck the eventListener inside my class:

window.addEventListener("keydown", this.MoveBlock);

 

 

Any ideas.

Link to comment
Share on other sites

Hello,

 

Your MoveBlock method gets correctly called (2 times for every instance).

 

The problem is that this inside the function is set to the window object and not your player object! I recommend to read articles about this, simply google something like "javascript function context"

 

Here is a quick fix:

window.addEventListener("keydown", this.moveBlock.bind(this));

The bind method returns the moveBock function with a fixed this (In this case your Player Object)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...