Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 38 期(W3C 标准-JavaScript-事件):事件的绑定与移除 #41

Open
wingmeng opened this issue Jun 21, 2019 · 0 comments
Open

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 21, 2019

题目:

JavaScript 中为 DOM 元素绑定事件可使用 addEventListener 来实现,但与之对应的事件移除方法 removeEventListener 却没有那么好用,例如它无法移除绑定的匿名方法。
请结合下面的代码,实现按钮点击一次后,移除自身绑定的匿名方法的功能。

var btn = document.createElement('button');
btn.innerText = '按钮';
btn.addEventListener('click', function() {
  btn.innerText = '我被点击了-' + (+new Date());
});
document.body.appendChild(btn);

参考答案:

window.HTMLElement && !function() {
  HTMLElement.prototype.addListener = function(type, fn, capture) {
    var el = this;
    fn = typeof fn === 'function' ? fn : function(){};

    var bind = function() {
      el.addEventListener(type, fn, capture);
      return {
        removeListener: function() {
          el.removeEventListener(type, fn);
        }
      }
    };

    return bind();
  }
}();

var btn = document.createElement('button');
btn.innerText = '按钮';
var evt = btn.addListener('click', function() {
  btn.innerText = '我被点击了-' + (+new Date());
  evt.removeListener();
});
document.body.appendChild(btn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant