Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has been nagging at me since its inception.
The Fun Project
Just for kicks, I decided to convert an ActionScript 3 text-based game engine into TypeScript and JavaScript using PixiJS. Currently, I have 20213 errors popping up while running tsc
, so I could postpone this task for later. Nonetheless, I started working on the Button class, defined as a subclass of MovieClip. I researched PIXI buttons, which seemed straightforward enough. All I needed to do was add similar lines of code within the button's constructor:
export class Button extends PIXI.Sprite {
private _callback : Function;
private _height : number;
private _width : number;
public get callback() : Function { return this._callback; }
public set callback(fn : Function) {this._callback = fn; }
public get height() : number { return this._height; }
public set height(h : number) {this._height = h; }
public get width() : number {return this._width; }
public set width(w : number) {this._width = w; }
public constructor(width = 180, height = 90, callback: Function = null){
super(new PIXI.Texture(new PIXI.BaseTexture(GLOBAL.BTN_BACK, PIXI.SCALE_MODES.NEAREST)));
this.callback = callback;
this.width = width;
this.height = height;
this.buttonMode = true;
this.interactive = true;
this.anchor.set(0.5);
this.on('mousedown', this.callback)
.on('touchstart', this.callback);
}
}
This simplified version differs slightly from the one on Codepen, which utilizes a Container and a private _sprite field instead. Regardless, the essence remains the same.
The Challenge
The issue arises when attempting the following on Codepen:
// assign `this.callback` to each of the following events:
let that = this;
['click','mousedown','touchstart'].map(evt => that.on(evt, that.callback});
I aimed to achieve this with a simple call passed into their constructors elsewhere:
for (let n = 0; n < 5; ++n){
btnArray.push(new Button(16, 16, () => console.info('You pushed button %d', n)));
}
However, nothing seems to be triggering, even when checking the Chrome Console. I even debugged the ColorMatrixFilter mentioned earlier to ensure the issue isn't related to console.info. As of now, I'm perplexed about where the problem lies. I initially thought of creating a GLOBAL key to iterate through for the events, but it doesn't seem to be functioning correctly.
The Queries
- Is my approach feasible, albeit unconventional? Could there be a security feature hindering it, or am I missing something crucial?
- Do I really need to stress over setting multiple event handlers, or would listening solely to 'click' suffice?