How would I go about recreating this with haxe?
actionscript looks like this:
public function Foobar()
{
for(var x:int = 1; x <= 10; x++)
{
this["cardPrint"+x] = new this["card_"+x]();
this.addChild(this["cardPrint"+x]);
this["cardPrint"+x].addEventListener(MouseEvent.CLICK, this["click_"+x]);
}
}
Been trying for hours but cannot seem to recreate this. Yes I tried google but I cannot find anything that points me in the right direction.
This comes up pretty often, so I really should do a blog post on it.
If you want to store a bunch of the same thing, and you want to identify them by number rather than name, then an array is what you want. You can create an array like so:
var deck:Array<Card> = [];
This array is empty, which isn’t much use. Let’s add some cards to it:
deck.push(new Card(0));
deck.push(new Card(1));
deck.push(new Card(2));
deck.push(new SpecialCard());
Now your array has four cards. You can check this by running trace(deck)
. Next up is adding the cards as children:
for(card in deck) {
addChild(card);
}
And finally, you want event listeners. While you could write out a bunch of different functions with a bunch of different names, it would be much more convenient if you could just take an argument:
private function onClickCard(card:Card, event:Event):Void {
trace(card + " was clicked!");
}
Wouldn’t that be nice? Fortunately, Haxe lets you do just that! Simply use the bind()
function when setting up your listeners:
for(card in deck) {
card.addEventListener(MouseEvent.CLICK, onCardClicked.bind(card));
}
3 Likes