1

Closed

Again : _this in closure

description

I know this has been addressed before, just could not find it now, sorry for repetition

Trying to create a query widget I need something like :
$.widget("app.somewidget", {_create:()=>{this.element...}});
typescript will convert "this" to "_this", but placing _this = this in a wrong place (topmost in the file) which of course does not work for the widget.

I found out this ugly workaround works:
var somewidget = {
    _create: () => {
        $("<span></span>").text("Something").insertAfter(this.element);
        () => { this } // weird workaround
    }
}
$.widget("app.somewidget", somewidget);
i.e. adding another closure to force typescript to add an extra _this=this, and this one on the right place:
var somewidget = {
    _create: function () {
        var _this = this;
        $("<span></span>").text("Something").insertAfter(_this.element);
        (function () {
            _this;
        });
    }
};
Sometimes it's just wrong by typescript to add _this=this. Perhaps it would be nice to have some notation to make typescript keep the original syntax?
        $("<span></span>").text("Something").insertAfter(@this.element);
Another ugly workaround to make typescript dont mind my 'this':
        $("<span></span>").text("Something").insertAfter(eval('this').element);
Closed Feb 11, 2013 at 5:37 PM by paulb
Closing as this is more a question.

comments

prgjonas wrote Feb 10, 2013 at 10:13 AM

"I would use a function, not a closure - wouldn't that solve this issue?" (Steve Fenton)

var somewidget = {
_create: function(){
    $("<span></span>").text("Something").insertAfter(this.element);
}
}

Indeed, works perfect, thanks Steve... I obviously need to refresh my knowledge about ()=> vs function in typescript.