javascript - 如何调用类中的方法抛出事件?

标签 javascript

我有一个需要在窗口中拖动的元素,具有功能的代码运行良好,但是当我使用类时,我无法理解为什么它不能。

你能帮我manipulate_this_element()吗?下面的codepen中的方法?

https://codepen.io/igor-sushko/pen/oNNBvQX?editors=1011

class View {
  create_staff() {
    console.log("staff work!");
    this.listener();
  };

  listener() {
    console.log("listener work!");
    let a = document.getElementById("AAA");
    a.addEventListener("mousedown", this.mouse_down)
    // .onmousedown = this.mouse_down();
  };

  mouse_down(e) {
    let that = this;
    console.log("mouse_down work!");
    e.preventDefault();
    document.addEventListener("mousemove",  that.manipulate_this_element)
    // document.onmousemove = this.manipulate_this_element();
  };

  manipulate_this_element() {
    console.log("manipulate_this_element work!");
  };
}

let a = new View();
a.create_staff();

我想看看“manipulate_this_element 工作!”当我移动鼠标时在控制台中

最佳答案

问题是,使用 a.addEventListener("mousedown", this.mouse_down) 时,事件发生时不会在 View 对象上调用 mouse_down,因此mouse_down 中的 this 不再引用 View 实例。

为了解决这个问题,您可以通过多种方式将 this 绑定(bind)到函数。

鉴于您已经使用了 class 那么您可能已经能够使用以下语法:

 mouse_down = (e) => {
 }

以这种方式使用箭头函数将会将该箭头函数的 this 绑定(bind)到 View 的实例。

此方法的一大优点是,这还允许您使用 a.removeEventListener("mousedown", this.mouse_down) 轻松删除事件监听器

完整代码如下:

class View {
  create_staff() {
    console.log("staff work!");
    this.listener();
  }

  listener() {
    console.log("listener work!");
    let a = document.getElementById("AAA");
    a.addEventListener("mousedown", this.mouse_down)
    // .onmousedown = this.mouse_down();
  }

  mouse_down = (e) => {
    let that = this;
    console.log("mouse_down work!");
    e.preventDefault();
    document.addEventListener("mousemove",  that.manipulate_this_element)
    // document.onmousemove = this.manipulate_this_element();
  }

  manipulate_this_element = () => {
    console.log("manipulate_this_element work!");
  }
}

let a = new View();
a.create_staff();

关于javascript - 如何调用类中的方法抛出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58485073/

相关文章:

javascript - 在 Internet Explorer 中打开链接

javascript - JS中 "?${new Date().getTime()} "如何更新图像

javascript - 使用 Greasemonkey 编译一系列单选按钮?

javascript - 使用javascript在浏览器中解析grep的结果

javascript - 如何将多项选择中选定的元素插入到输入中?

javascript - 如何使SharePoint任务列表的新任务表单中的所有字段都可见?

javascript - 纯粹使用 Javascript 构建集成测试并在浏览器中运行是一个坏主意吗?

javascript - 使用AJAX加载元素时重新加载JS函数

javascript - Vue 用 [] 括号打印我的数组,为什么?

javascript - 使用 Sharepoint 查询字符串值作为应用程序部分属性