Search code examples
javascriptjqueryoopevent-listener

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


I am using addBtn.on('click', list.addItem.bind(list));. How can I get the event parameter so that I can implement the event.preventDefault() inside addItem(){}. is there a way to do that?

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));

Solution

  • You do it exactly the way you would have done it without using bind: by accepting the parameter:

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

    The function bind returns calls the original function with all of the arguments it receives, so it passes the event to your method.

    Live Example:

    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>