使用 Bind 方法时使用 eventListener 获取 EVENT 参数 (class)

getting the EVENT parameter with eventListener while using Bind method (class)

我正在使用 addBtn.on('click', list.addItem.bind(list));。如何获取event参数,以便在addItem(){}中实现event.preventDefault()。有办法吗?

const addBtn = $('#addBtn'),
  itemListText = $('#itemListText'),
  textInput = $('#addToListInput');

class Lists {
  constructor() {
    this.currentList = [];
  }

  currentListCount() {
    return this.currentList.length;
  }

  addItem() {
    if (textInput.val().length > 0)
      this.currentList.push({
        item: textInput.val(),
        checked: 'false',
      });

    itemListText.text(`Item List (${this.currentListCount()})`);
    textInput.val('');
  }
}

const list = new Lists();

addBtn.on('click', list.addItem.bind(list));

您完全按照不使用 bind 的方式进行操作:通过接受参数:

addItem(event) {
    // ...use `event.preventDefault()` etc. here...
}

函数 bind returns 使用它接收到的所有参数调用原始函数,因此它将事件传递给您的方法。

实例:

const addBtn = $('#addBtn'),
  itemListText = $('#itemListText'),
  textInput = $('#addToListInput');

class Lists {
  constructor() {
    this.currentList = [];
  }

  currentListCount() {
    return this.currentList.length;
  }

  addItem(event) {
    event.stopPropagation();
    if (textInput.val().length > 0)
      this.currentList.push({
        item: textInput.val(),
        checked: 'false',
      });

    itemListText.text(`Item List (${this.currentListCount()})`);
    textInput.val('');
  }
}

const list = new Lists();

addBtn.on('click', list.addItem.bind(list));

$("#wrapper").on("click", () => {
    console.log("Wrapper saw click event");
});
All of the elements below are in a wrapper that logs when it sees a click. Notice that it sees clicks every except when you click the Add button, because the Add button uses <code>stopPropagation</code> on the event object it receives.
<div id="wrapper">
  <div id="itemListText">Item List (0)</div>
  <input type="text" id="addToListInput">
  <input type="button" id="addBtn" value="Add">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>