so I’m working on recreating the card game Dominion in Javascript. I’m using OO Javascript, creating a card object for each card.
Rather than posting all my code here I’ll save some space and link you to it:
Site:
http://people.rit.edu/lxl1500/Prog4/Project%201/project1.html
Script:
http://people.rit.edu/lxl1500/Prog4/Project%201/main-script.js
Where I’m running into issues:
In my createActions() function I’m adding an onclick event to each image (I’m creating the images by grabbing the smallImage property of each object). This onclick should call my fullImage() function. This function will simply show a larger version of the card so the player can see the details. Therefore, I want to pass the image property, which holds the string for the source of the larger image to the function.
fullImage() will accept the object property as imageSrc. You’ll see now by clicking on an image you’ll get an alert of undefined. The only thing I can think of is when I’m calling fullImage(this.image) – this is reference to the image itself rather than the object…I’m not sure how to accomplish what I’m trying to do though. Any help would be greatly appreciated!
Thank you for your time.
You’re setting
onclickas an attribute. You might be able to work with that somehow, but it’s a much more elegant solution to attach an event listener:Then you can use
actionCards[i]as normal… except you can’t, becauseiwill be one over the last index, for reasons I won’t get into here.1 The easiest way to fix that is to bind the function before you add it as an event listener:(I should note that
bindis not built-in in some older browsers. While I’m on the topic of browser compatibility,addEventListenerisn’t supported by old versions of Internet Explorer, either.) Then you can usethisto refer to yourCardobject.Footnotes
1 Okay, fine. It’s because of JavaScript’s function scope and that when the user has clicked it, the loop has finished, and when the loop has finished,
iwill be one over the number of cards.