How can I preserve lexical scope in TypeScript with a callback function

前端 未结 5 2090
小蘑菇
小蘑菇 2020-11-29 01:01

I have a TypeScript class, with a function that I intend to use as a callback:

removeRow(_this:MyClass): void {
    ...
    // \'this\' is now the window obj         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 01:50

    Use .bind() to preserve context within the callback.

    Working code example:

    window.addEventListener(
      "resize",
      (()=>{this.retrieveDimensionsFromElement();}).bind(this)
    )
    

    The code in original question would become something like this:

    $.ajax(action, {
        data: { "id": id },
        type: "POST"
    })
    .done(
      (() => {
        removeRowCallback();
      }).bind(this)
    )
    

    It will set the context (this) inside the callback function to whatever was passed as an argument to bind function, in this case the original this object.

提交回复
热议问题