事件未使用功能绑定定义

时间:2019-02-27 04:49:24

标签: javascript events bind

class Foo {
    construtor(){
        this.ref = document.querySelector('.foo');
        this.bind('click', onClick)
    }
    onClick(event) {
        // event is undefined
        console.log(event)
    }
    bind(event,action) {
        this.ref.addEventListener(event, action.bind(this));
    }
}

请告诉我事件参数如何传递给onClick函数。

2 个答案:

答案 0 :(得分:1)

利用闭包的优势:

c:\ngrok>ngrok authtoken c:/ngrok <authtoken>
Authtoken saved to configuration file: C:\Users\kim/.ngrok2/ngrok.yml

答案 1 :(得分:0)

以下演示可以将多个元素与任何适用的事件和回调绑定在一起。

演示

article

中的代码的修改版本

class Binder {

  constructor(selector) {
    const elements = document.querySelectorAll(selector);
    this.length = elements.length;
    Object.assign(this, elements);
  }

  each(callback) {
    for (let node of Array.from(this)) {
      callback.call(node);
    }
    return this;
  }

  bind(event, callback) {
    return this.each(function() {
      this.addEventListener(event, callback, false);
    });
  }
};


const eH = selector => new Binder(selector);
const eL = element => new Binder(element);

let count = 0;

const clickCount = e => {
  const eTgt = e.currentTarget.children[0];
  count++;
  eTgt.textContent = count;
};

const colorRed = e => {
  e.target.style.color = 'red';
};

eH('.node').bind('click', clickCount);

eL('.tag').bind('click', colorRed);
.node,
.tag {
  display: inline-block;
  width: 110px;
  height: 54px;
  padding: 8px;
  border: 1px solid #000;
  text-align: center;
  font-size: 48px;
  cursor: pointer;
}

*:focus {
  outline: none;
}
<div class='node'><b>0</b></div>

<div class='tag'>TAG</div>

<div class='tag node'><b>TAG</b></div>