javascript - 带绑定(bind)的事件委托(delegate)? (Javascript)

标签 javascript

您知道有时您想对多个元素使用一个事件监听器吗?像这样:

divWithManyLinks.addEventListener("click", function(event) {
    console.log(event.target.textContent);
}
//--> text content of the clicked link 

您知道有时您想将绑定(bind)与事件监听器一起使用来更改事件处理程序的范围吗?例如,您可能需要引用“this”并指向特定的内容。

如果你想为多个元素使用一个事件监听器并同时使用绑定(bind),这可能吗?

就我而言,我希望能够根据以下内容从一种方法 (Example.prototype.methodA) 转到同一对象中的其他两种方法之一(Example.prototype.methodB 或 Example.prototype.methodC)单击按钮。因为事件监听器放置在 methodA 内部,所以其他方法将通过 this.methodB 和 this.methodC 引用。我可以分别实现两个带有绑定(bind)的事件监听器,但是是否可以只有一个事件监听器?

Example.prototype.methodA = function() {
    // addEventListener that listens on both buttons and executes either this.methodB or this.methodC based on what button is clicked.
}

Example.prototype.methodB = function() {
    // do stuff
}

Example.prototype.methodC = function() {
    // do stuff
}

如果这是不好的做法或者有更好的方法,请告诉我。

最佳答案

你可以做到这一点,是的。这是一个例子:

Example.prototype.methodA = function() {
    someContainerElement.addEventListener("click", function() {
        if (/* `event.target` is a match for the first button*/) {
            this.methodB();
        } else {
            this.methodC();
        }
    }.bind(this), false);
};

当然,它不一定是 if,可以是 switch 或 map 查找或...

实例:

function Example(element, name) {
  this.name = name;
  this.element = element;
  this.output = element.querySelector(".output");
}
Example.prototype.methodA = function() {
  this.element.addEventListener("click", function() {
    if (event.target.name == "B") {
      this.methodB();
    } else {
      this.methodC();
    }
  }.bind(this), false);
}

Example.prototype.methodB = function() {
  this.output.innerHTML =
    prep(this.name).toLowerCase();
};

Example.prototype.methodC = function() {
  this.output.innerHTML =
    prep(this.name).toUpperCase();
};

function prep(text) {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;");
}

new Example(document.getElementById("one"), "one").methodA();
new Example(document.getElementById("two"), "two").methodA();
<div id="one">
  The "one" element:
  <br>
  <input type="button" name="B" value="Lower">
  <input type="button" name="C" value="Upper">
  <span class="output"></span>
</div>
<div id="two">
  The "two" element:
  <br>
  <input type="button" name="B" value="Lower">
  <input type="button" name="C" value="Upper">
  <span class="output"></span>
</div>

关于javascript - 带绑定(bind)的事件委托(delegate)? (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34401410/

相关文章:

javascript - FullCalendar gotoDate 丢失多个日历的放置事件

javascript - 如何从 node-xmpp 请求中获取响应?

javascript - knockout foreach 绑定(bind),更新值

javascript - 如何防止规范 URL

javascript - 下载50%后开始播放视频

Javascript 缩小或压平对象?

javascript - Bootstrap 水平滚动 spy ?

javascript - 绑定(bind)多个事件时调用特定函数

javascript - 在codeigniter中将数据从javascript传递到php文件

javascript - 从 postgres 数据库中获取 Node js 中的多个 Refcursor(使用 pg-promise)