首页 > 解决方案 > 如何从 JQuery datepicker select 调用 typescript 函数

问题描述

我如何从下面的选择中调用 updateFunc。

ngAfterViewChecked() {
    $(".datepicker").datepicker({
      changeMonth: true,
      changeYear: true,
     onSelect: function (selected, evnt) {
        this.updateFunc(evnt);
      }
    });
}

updateFunc(evnt: any) {
    alert("hi");
}

这不起作用,我应该使用 => 调用另一个函数,this.function 不起作用?

标签: angulartypescript

解决方案


您回答了自己的问题,但是是的,不是使用function标签编写 onSelect ,而是使用箭头函数,它将保留 this 的范围到它被调用的位置。当您使用function关键字时,您正在创建一个新范围,其中this将引用该函数范围内的变量。

箭头函数是这里的方法,但在这些方法出现之前的一些较旧的方法将.bind(this)在创建该函数之前使用或执行类似的操作。

let self = this;  // create a reference to 'this' above isolate scope.
onSelect: function(selected,evnt){
    self.updateFunc(event)
};

使用箭头功能,您不必这样做,只需执行以下操作:

onSelect:(selected,evnt) => { //arrow function passes the this into the new scope
    this.updateFunc(event)
}

推荐阅读