Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bind function and this in typescript

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?

like image 832
Seb Bizeul Avatar asked Dec 28 '15 19:12

Seb Bizeul


1 Answers

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);
like image 102
CoderPi Avatar answered Sep 22 '22 12:09

CoderPi