如何将事件与OOP JS绑定

时间:2018-07-16 14:23:17

标签: javascript ecmascript-6

我需要将Blur事件绑定到带有JS的方法中,并检索对象数据。那就是我得到的:

class TestClass {
    constructor(input) {
        this.inputTest = input;

        this.objectTest = {
            1: "one",
            2: "two",
            3: "three"
        }

        this.isBinded = false;
    }

    test() {
        if(!this.isBinded) {
            this.inputTest.addEventListener("blur", function( event ) {
                alert("Test Event");

                // I need to access to Object Scope, but seems not to be working
                console.log(this.objectTest);
            });
        }

        this.isBinded = true;
    }
}

var test = new TestClass(document.querySelector("input"));
test.test();

所以,这是我需要的一个简单示例。我只有一个输入,当我初始化类时,我绑定了一个blur事件。当我尝试它时,它只是向我显示警报,因此显然可以正常工作。

但是,似乎它无法访问对象范围,因为它没有从对象范围返回this.objectTest对象示例。

有人可以帮助我吗?谢谢

2 个答案:

答案 0 :(得分:0)

由于您在addEventListener中使用常规函数,因此将其重新绑定到inputTest元素。您需要使用箭头函数将其保留为类对象。像这样:

this.inputTest.addEventListener("blur", ( event ) => {
            alert("Test Event");

            // I need to access to Object Scope, but seems not to be working
            console.log(this.objectTest);
        });

答案 1 :(得分:0)

  

但是,似乎它无法访问对象范围,因为它没有从对象范围返回this.objectTest对象示例

是的,实际上在addEventListener回调中,this指的是要将事件附加到的input,因此this.objectTest将是undefined,因为它没有引用您班级的objectTest属性。

您需要做的是对类this的引用,以便您可以在回调中访问它,可以将其分配给另一个变量,如下所示:

test() {
 var _self = this;
    if(!this.isBinded) {
        this.inputTest.addEventListener("blur", function( event ) {
            alert("Test Event");

            // I need to access to Object Scope, but seems not to be working
            console.log(_self.objectTest);
        });
    }

    this.isBinded = true;
}

演示:

这是一个演示其工作原理的演示。

class TestClass {
  constructor(input) {
    this.inputTest = input;

    this.objectTest = {
      1: "one",
      2: "two",
      3: "three"
    }

    this.isBinded = false;
  }



  test() {
    var _self = this;
    if (!this.isBinded) {
      this.inputTest.addEventListener("blur", function(event) {
        alert("Test Event");

        // I need to access to Object Scope, but seems not to be working
        console.log(_self.objectTest);
      });
    }

    this.isBinded = true;
  }
}

var test = new TestClass(document.getElementById("js-test"));
test.test();
Check it : <input id="js-test" />