การรับฟังเหตุการณ์
สมัครรับบันทึก
การรับฟังเหตุการณ์ เป็นบทเรียน Web3 & DApp Development Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Web3 & DApp Development Fundamentals และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Are Events
Smart contracts emit events to log that something happened — a transfer, an approval, a vote. Events are written to the transaction's logs.
- They are cheaper than storage.
- Off-chain apps subscribe to them to stay in sync.
Events in the ABI
To decode events, ethers needs their definitions in the ABI:
const abi = [
"event Transfer(address indexed from, address indexed to, uint256 value)",
];
const contract = new ethers.Contract(address, abi, provider);The indexed keyword marks fields you can filter on.
const abi = [
"event Transfer(address indexed from, address indexed to, uint256 value)",
];
const contract = new ethers.Contract(address, abi, provider);Listening Live
Subscribe to new events with on. The callback fires whenever the event is emitted:
contract.on("Transfer", (from, to, value, event) => {
console.log(from, "->", to, value);
});This needs a provider that supports subscriptions, such as a WebSocket connection.
contract.on("Transfer", (from, to, value, event) => {
console.log(from, "->", to, value);
});WebSocket Providers
Live subscriptions work best over a persistent connection. Use a WebSocket provider:
const provider = new ethers.WebSocketProvider(
"wss://mainnet.example-rpc.io/KEY"
);HTTP providers can poll for events but a WebSocket pushes them in real time.
const provider = new ethers.WebSocketProvider(
"wss://mainnet.example-rpc.io/KEY"
);Listening Once
If you only care about the first occurrence, use once:
contract.once("Approval", (owner, spender, value) => {
console.log("First approval seen");
});The listener automatically removes itself after firing a single time.
contract.once("Approval", (owner, spender, value) => {
console.log("First approval seen");
});Querying Past Events
To read historical events, use queryFilter over a block range:
const logs = await contract.queryFilter(
"Transfer",
19000000,
19000100
);
for (const log of logs) {
console.log(log.args.from, log.args.value);
}Each log exposes decoded args.
const logs = await contract.queryFilter(
"Transfer",
19000000,
19000100
);
for (const log of logs) {
console.log(log.args.from, log.args.value);
}Filtering by Indexed Fields
Build a filter to match specific indexed values — for example transfers to one address:
const filter = contract.filters.Transfer(null, myAddress);
const logs = await contract.queryFilter(filter);Passing null means match any value for that position.
const filter = contract.filters.Transfer(null, myAddress);
const logs = await contract.queryFilter(filter);Live Filtered Listening
You can also pass a filter to on to react only to relevant events:
const filter = contract.filters.Transfer(null, myAddress);
contract.on(filter, (from, to, value) => {
console.log("Received:", value);
});This avoids processing events you do not care about.
const filter = contract.filters.Transfer(null, myAddress);
contract.on(filter, (from, to, value) => {
console.log("Received:", value);
});Removing Listeners
Long-running apps should clean up listeners to avoid leaks:
contract.off("Transfer", myHandler);
// or remove all listeners for an event
contract.removeAllListeners("Transfer");Always remove listeners when a component unmounts or a job finishes.
contract.off("Transfer", myHandler);
// or remove all listeners for an event
contract.removeAllListeners("Transfer");Handling Reorgs
Recent events can be reverted if the chain reorganizes. For reliable indexing:
- Wait several confirmations before treating an event as final.
- Track the block number and re-process if a reorg is detected.
This keeps your off-chain database consistent with the chain.
Provider-Level Log Filters
You can also subscribe at the provider level without a contract instance, using a raw log filter by topic:
provider.on({
address: tokenAddress,
topics: [ethers.id("Transfer(address,address,uint256)")],
}, (log) => {
console.log("Raw log:", log);
});This is lower-level but works across many contracts at once.
provider.on({
address: tokenAddress,
topics: [ethers.id("Transfer(address,address,uint256)")],
}, (log) => {
console.log("Raw log:", log);
});Quick Check
Test your understanding of event handling.
Recap
You learned to work with contract events.
- Events log on-chain activity to transaction logs.
onsubscribes live (best over a WebSocket provider);oncefires a single time.queryFilterreads historical events over a block range.- Build filters from indexed fields; pass
nullto match any. - Remove listeners to avoid leaks and wait for confirmations against reorgs.
คำถามที่พบบ่อย
บทเรียน “การรับฟังเหตุการณ์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การรับฟังเหตุการณ์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web3 & DApp Development Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การรับฟังเหตุการณ์”
สมัครรับบันทึก คุณปฏิบัติ Web3 & DApp Development Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web3 & DApp Development Fundamentals หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web3 & DApp Development Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การรับฟังเหตุการณ์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Web3 & DApp Development Fundamentals นี้ได้ไหม
ได้ บทเรียน Web3 & DApp Development Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเชื่อมต่อกับผู้ให้บริการ
- การอ่านข้อมูลสัญญา
- การส่งธุรกรรม
- การรับฟังเหตุการณ์