如何为 provider.on(eventName, listener) 定义侦听器参数以使用 ethers.js 侦听智能合约事件?

How to define listener argument for provider.on(eventName, listener) for listening a smart contract event with ethers.js?

我正在按照这个快速指南前往 build a Dapp

为了构建用户界面并与智能合约交互,它使用了 React。有以下功能:

async function submitBid(event) {
   event.preventDefault();
   if (typeof window.ethereum !== 'undefined') {
     const contract = await initializeProvider();
     try {
       // User inputs amount in terms of Ether, convert to Wei before sending to the contract.
       const wei = parseEther(amount);
       await contract.makeBid({ value: wei });
       // Wait for the smart contract to emit the LogBid event then update component state
       contract.on('LogBid', (_, __) => {
         fetchMyBid();
         fetchHighestBid();
       });
     } catch (e) {
       console.log('error making bid: ', e);
     }
   }
 }

 async function withdraw() {
   if (typeof window.ethereum !== 'undefined') {
     const contract = await initializeProvider();
     // Wait for the smart contract to emit the LogWithdrawal event and update component state
     contract.on('LogWithdrawal', (_) => {
       fetchMyBid();
       fetchHighestBid();
     });
     try {
       await contract.withdraw();
     } catch (e) {
       console.log('error withdrawing fund: ', e);
     }
   }
 }

根据 ethers.js library,为了监听智能合约事件,它需要 provider.on(eventName, listener),但我想知道为什么在这种情况下对于监听器参数它使用 (_)(_, __),这意味着什么?如果回调函数对于两个函数几乎相同,那么为什么两者不同,这些都是要考虑的智能合约事件:

event LogBid(address indexed _highestBidder, uint256 _highestBid);
event LogWithdrawal(address indexed _withdrawer, uint256 amount);

在 lamda 函数中命名变量 _ 的一般约定是表明您不会使用将传递给 lamda 的参数,但 lamda 的使用者仍然期望传入变量。

话虽这么说...javascript 不需要您这样做,如果两个听众都不希望有任何争论,实际上会工作得很好。

需要注意的是

中的_
contract.on('LogBid', (_, __) => {
         // _ is the unused param 'highestBidder'
         // __ is the unused param highest bid
         fetchMyBid();
         fetchHighestBid();
       }

中的_
contract.on('LogWithdrawal', (_) => {
       // _ is the address of who withdrawed
       // If lamda supplied another var it would hold the amount withdrawn
       fetchMyBid();
       fetchHighestBid();
     });

不是同一个值。