简体   繁体   English

当作为参数传递时,对象方法回调在事件处理程序中失去其绑定,但在硬编码时不会

[英]Object-method callback loses its binding in an event handler when passed as a parameter, but not when hard-coded

I'm new to Javascript OOP and have a question about binding to callbacks in event handlers.我是 Javascript OOP 的新手,有一个关于绑定到事件处理程序中的回调的问题。

I'm trying to apply an event handler to a DOM element in my constructor function.我正在尝试将事件处理程序应用于构造函数中的 DOM 元素。 The event-handler function is a method of the object, and I'm attempting to pass a callback function (also a method of the same object) to that handler.事件处理函数是对象的方法,我试图将回调函数(也是同一对象的方法)传递给该处理程序。

When I hard code the callback inside the handler (using this.callbackMethod()) it runs as expected:当我在处理程序中硬编码回调时(使用 this.callbackMethod()),它按预期运行:

class Foo {
  constructor (name){
    this.name = name
    this.bar();
  }
  callback(){
    console.log(this.name + 'bar callback this:') // 'foobar callback this:
    console.log(this) // Foo object with name 'foo'
  }
  bar(){
    document.querySelector('button').addEventListener('click', function(){
      console.log('bar click event this:')
      console.log(this)
      // this is the relevant line
      this.callback()
    }.bind(this));
  }
}

const foo = new Foo('foo');

However, when I pass that parameter as a callback, even if I use .bind(this) on both the callback and the handler, it fails:但是,当我将该参数作为回调传递时,即使我在回调和处理程序上都使用 .bind(this) ,它也会失败:

class Foo {
  constructor (name){
    this.name = name
    this.bar(this.callback);
  }
  callback(){
    console.log(this.name + 'bar callback this:')// Uncaught TypeError: Cannot read property 'name' of undefined
    console.log(this)
  }
  bar(cb){
    document.querySelector('button').addEventListener('click', function(){
      console.log(cb)// logs function definition
      // this is the relevant line
      cb().bind(this); 
    }.bind(this));
  }
}

const foo = new Foo('foo');

Codepen examples:代码笔示例:
Hard-coded callback: https://codepen.io/RandomNeuralFiring/pen/Pgrdey硬编码回调: https : //codepen.io/RandomNeuralFiring/pen/Pgrdey
Parameter callback: https://codepen.io/RandomNeuralFiring/pen/QPXVOR参数回调: https : //codepen.io/RandomNeuralFiring/pen/QPXVOR

I want the option of re-using bar() with other callbacks, so would love to understand how I can set its context dynamically.我想要将 bar() 与其他回调一起使用的选项,所以很想了解我如何动态设置其上下文。

PS I couldn't find a suitable tag for object-binding - perhaps one should be created? PS 我找不到适合对象绑定的标签 - 也许应该创建一个?

您正在bind cb返回值- 尝试先绑定函数然后调用它:

cb.bind(this)(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM