为什么这个ts类没有按预期运行

时间:2018-01-28 14:36:36

标签: jquery typescript addeventlistener

在这段代码中,我的愿望是:

  • 获取模板($ .get(...)),
  • 将输入上的eventListener绑定到模板

使用webpack来转换代码,没有问题。

代码:

import * as $ from 'jquery';

export class TodoForm {
private _input: Element;

constructor(element: JQuery){
    $(function() {
        $.get('./src/Components/todoForm/todoForm.html', (data) => {
            $(element).append(data);

            // Définit le listener sur la zone de saisie
            this._input = document.getElementById('todoContent');
            this._input.addEventListener('keyup', this._setInputListener);
        });
    });
}

private _setInputListener(event: any): void {
    alert('COucou input');
    let _input = $(this._input);
    if(_input.val().length > 0){
        console.log('Active le bouton d\'ajout')
    } else {
        console.log('Désactive le bouton')
    }
}
}

当运行时...任何警报,任何控制台,如果输入字段上的键盘...

不明白为什么......

1 个答案:

答案 0 :(得分:0)

您在非箭头功能上使用this

import * as $ from 'jquery';

export class TodoForm {
  private _input: Element;

  constructor(element: JQuery) {
    $(() => { // You need an arrow function here
      $.get('./src/Components/todoForm/todoForm.html', data => {
        $(element).append(data);

        // Définit le listener sur la zone de saisie
        this._input = document.getElementById('todoContent');
        this._input.addEventListener('keyup', this._setInputListener);
      });
    });
  }

  // This way the function is auto bind to the instance
  private _setInputListener = (event: any): void => {
    alert('COucou input');
    let _input = $(this._input);
    if (_input.val().length > 0) {
      console.log("Active le bouton d'ajout");
    } else {
      console.log('Désactive le bouton');
    }
  };
}
相关问题