I wanted to implement a simple context binding but it doesn't work in TypeScript. Here is my piece of code:
class Engine {
// some code...
spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
callbackfn.bind(new SpriteController(sprite), [this._ctx]);
}
// code again ...
}
If I want to use spriteController method in another file like this:
engine.spriteController(sprite, function(ctx) {
this.moveRight() // access to the spriteController class
})
I want to be able to use the SpriteController class within the callback.
In JS, the first argument (within the bind() call) bind 'this' to the given object. But in TypeScript, functions created from function.bind are always preserve 'this'.
How to achieve this in TypeScript?
When binding, it is returning the bound function, you have to update your variable width callbackfn = callbackfn.bind(...)
:
Documentation link
class Engine {
spriteController(sprite: Sprite, callbackfn: (ctx: CanvasRenderingContext2D) => void) {
let callbackfnBinded = callbackfn.bind(new SpriteController(sprite), [this._ctx])
callbackfnBinded()
}
}
JavaScript here:
var Sprite = (function () {
function Sprite(name) {
this.name = name;
}
return Sprite;
})();
var SpriteController = (function () {
function SpriteController(sprite) {
this.sprite = sprite;
}
return SpriteController;
})();
var Engine = (function () {
function Engine() {
}
Engine.prototype.spriteController = function (sprite, callbackfn) {
callbackfn = callbackfn.bind(new SpriteController(sprite), [this._ctx])
callbackfn()
};
return Engine;
})();
var e = new Engine();
var s = new Sprite("test");
var cb = function (ctx) {
alert(this.sprite.name);
};
e.spriteController(s, cb);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With