Estoy usando addBtn.on('click', list.addItem.bind(list)); . ¿Cómo puedo obtener el parámetro de event para poder implementar event.preventDefault() dentro addItem(){} . ¿Hay una manera de hacer eso?
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));Lo haces exactamente de la forma en que lo hubieras hecho sin usar bind : aceptando el parámetro:
addItem(event) { // ...use `event.preventDefault()` etc. here... } La función bind return llama a la función original con todos los argumentos que recibe, por lo que pasa el evento a tu método.
Ejemplo en vivo:
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>