เพื่อให้เห็นภาพการทำงานของ MVP ชัดเจนที่สุด เขียนตัวอย่างด้วย JavaScript โดยทำระบบ “เครื่องนับเลข ” แบบง่าย ๆ ครับ
หัวใจสำคัญของ MVP คือ View และ Model จะไม่รู้จักกันเลย ทุกอย่างต้องวิ่งผ่าน Presenter ทั้งหมด
Model
มีหน้าที่แค่เก็บข้อมูลและจัดการตรรกะ ไม่สนว่าหน้าจอเป็นยังไง
JavaScript
class CounterModel { constructor () { this.count = 0; } // ตรรกะทางธุรกิจ: การเพิ่มค่า increment () { this.count++; } // ส่งคืนข้อมูลปัจจุบัน getCount () { return this.count; }
}
มีหน้าที่จัดการ HTML รับการคลิกจากผู้ใช้ และมีฟังก์ชันเตรียมไว้ให้ Presenter มาสั่งงาน
class CounterView { constructor () { // สมมติว่าใน HTML มี <h1 id="counter-display">0</h1> และ <button id="add-btn">Add</button> this.displayElement = document.getElementById ('counter-display') ; this.buttonElement = document.getElementById ('add-btn') ; } // เปิดช่องทางให้ Presenter เอาฟังก์ชันมาผูกกับปุ่ม bindIncrementEvent (handler) { this.buttonElement.addEventListener ('click', () => { handler () ; // เมื่อถูกคลิก จะเรียกฟังก์ชันที่ Presenter ส่งมาให้ }) ; } // เปิดช่องทางให้ Presenter สั่งอัปเดตหน้าจอ render (count) { this.displayElement.innerText = `จำนวนปัจจุบัน: ${count}`; }
}