Mô hình MVC (Model – View – Controller) là một kiến trúc phần mềm giúp tách biệt các thành phần của ứng dụng để dễ phát triển, quản lý và mở rộng.

Dưới đây là giải thích MVC trong JavaScript, áp dụng được cho cả phía client (trình duyệt) và server (Node.js).
Tóm tắt MVC
- Model: Quản lý dữ liệu và logic nghiệp vụ.
- View: Giao diện người dùng (UI).
- Controller: Trung gian giữa View và Model, xử lý yêu cầu và điều phối dữ liệu.
1. Model (M)
- Chứa dữ liệu và logic xử lý dữ liệu.
- Không biết gì về UI (View).
- Ví dụ: xử lý danh sách sản phẩm, kết nối cơ sở dữ liệu, validate dữ liệu,…
// model/Product.js
class Product {
constructor(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
static all() {
// giả lập database
return [
new Product(1, “iPhone”, 1000),
new Product(2, “Samsung”, 900),
];
}
}
export default Product;
2. View (V)
- Hiển thị dữ liệu (UI) cho người dùng.
- Không xử lý logic hoặc thay đổi dữ liệu trực tiếp.
- Có thể là HTML, template engine (EJS, Handlebars…), hoặc code DOM thuần.
<!– views/products.html –>
<ul id=”product-list”></ul>
<script>
function renderProducts(products) {
const list = document.getElementById(“product-list”);
list.innerHTML = “”;
products.forEach(p => {
const li = document.createElement(“li”);
li.textContent = `${p.name} – $${p.price}`;
list.appendChild(li);
});
}
</script>
3. Controller (C)
- Nhận yêu cầu từ người dùng (click, submit, API call…).
- Gọi Model để lấy hoặc thay đổi dữ liệu.
- Gọi View để cập nhật giao diện.
// controller/ProductController.js
import Product from “../model/Product.js”;
function showProducts() {
const products = Product.all();
renderProducts(products); // Gọi View để hiển thị
}
document.addEventListener(“DOMContentLoaded”, showProducts);
Tổng kết quy trình:
- Người dùng mở trang => Controller chạy.
- Controller gọi Model lấy dữ liệu.
- Controller gửi dữ liệu cho View.
- View hiển thị ra màn hình.
Giảng viên Võ Văn Mỹ
Bộ môn Công nghệ thông tin
FPT Polytechnic TP HCM

