In Ethers.js, both on
and once
are methods used to listen for events emitted by smart contracts. However, they serve different purposes in how they handle event listeners.
Understanding on
The on
method is used to register an event listener that will be called every time the specified event is emitted. This means that the listener will remain active and continue to respond to the event indefinitely until it is explicitly removed.
Example of on
const { ethers } = require('ethers');
// Connect to the Ethereum network
const provider = new ethers.providers.JsonRpcProvider('https://your.ethereum.node');
// Contract ABI and address
const abi = [
"event ValueChanged(address indexed author, string oldValue, string newValue)"
];
const contractAddress = '0xYourContractAddress';
// Create a contract instance
const contract = new ethers.Contract(contractAddress, abi, provider);
// Listen for the ValueChanged event using on
contract.on("ValueChanged", (author, oldValue, newValue) => {
console.log(`Value changed by ${author}: from "${oldValue}" to "${newValue}"`);
});
Understanding once
The once
method, on the other hand, registers an event listener that will be called only the first time the specified event is emitted. After the first invocation, the listener is automatically removed, meaning it will not respond to subsequent emissions of the event.
Example of once
once
1
Key Differences
- Persistence:
on
: The listener remains active and will respond to every event emission.once
: The listener is removed after the first event emission.
- Use Cases:
on
: Useful for ongoing monitoring of events, such as tracking state changes in real-time.once
: Ideal for one-time actions, such as initializing a process or responding to a specific event that only needs to be handled once.
Conclusion
Choosing between on
and once
depends on the specific requirements of your application. Use on
for continuous event listening and once
for single-event handling to optimize performance and resource usage.