所有。如果我只想复制代码,那么我可以解决一个问题,这可以简单地解决。我的意思是,真的,这只是项目的一小部分,我只是为了看看我能否,而不是其他任何东西,但是是打扰我,因为我我已经想到了。
为了好玩,我决定采用某人的ActionScript 3,基于文本的游戏引擎,并使用PixiJS将其转换为TypeScript,最终转换为JavaScript。
问题是,还有20213个错误需要修复才能运行tsc
,所以我可以把它留到以后的日期。但是我正在研究Button类,它们被定义为MovieClip的子类。没关系;我只是通过阅读PIXI按钮来回应,它们看起来相当简单。只是,在按钮的构造函数中,添加类似于以下行的内容:
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);
}
}
这是一个简化版本,我在Codepen上执行的版本使用了Container
和私有_sprite
字段(以及不起作用的ColorMatrixFilter)我选择的黑色图标太好了,但这对于这个问题并不重要),但这大致就是它如何完成的要点。
问题是,在codepen中,我想做以下事情:
// assign `this.callback` to each of the following events:
let that = this;
['click','mousedown','touchstart'].map(evt => that.on(evt, that.callback});
在其他地方的构造函数中传递一个简单的调用:
for (let n = 0; n < 5; ++n){
btnArray.push(new Button(16, 16, () => console.info('You pushed button %d', n)));
}
但即使在Chrome控制台中,我也没有从中获取任何内容。我甚至记录了我前面提到的ColorMatrixFilter,看看它是console.info
是不对的。不。所以现在,我对此感到困惑。我希望能够只使用GLOBAL
(来自AS源的遗留静态对象)键来迭代事件,但看起来似乎没有发生。
click
?答案 0 :(得分:1)
当执行类似于事件映射的箭头函数时,未设置this
上下文,因此引用this
的任何代码都将获取当前值,包括地图调用的任何函数。 / p>
使用以下内容替换您的活动地图:
['click','mousedown','touchstart'].map(function(evt) { that.on(evt, that.callback} } );
示范:
function Named(x) {
this.name = x;
}
var foo = new Named("foo");
var bar = new Named("bar");
var showFunc = function show() {
// this is context dependant
console.log(this.name);
}
var showArrow;
// this is the window
showArrow = () => console.log(this.name);
var fooShowArrow;
(function() {
// this is foo
that = this;
fooShowArrow = () => console.log(that.name);
}).apply(foo);
var example = function(func) {
// For the demo, at this point, this will always be bar
func.apply(this, [ "arbitrary value" ]);
}
// explicitly set the current "this" to bar for the execution of these functions
example.apply(bar, [showFunc]); // works
example.apply(bar, [showArrow]); // fails, this is still the window
example.apply(bar, [fooShowArrow]); // fails, this is still foo