MVP (Model-View-Presenter)
MVP nima?
Section titled “MVP nima?”MVP (Model-View-Presenter) — bu asosan foydalanuvchi interfeysi (UI) bor ilovalarda qo’llaniladigan arxitektura patternidir. U MVC ning o’zgargan ko’rinishi bo’lib, View va Model ni butunlay ajratishga qaratilgan.
Asosiy komponentlar:
- Model: Ma’lumotlar va biznes logika.
- View: Foydalanuvchi interfeysi (UI). U juda “passiv” bo’ladi.
- Presenter: Model va View o’rtasidagi vositachi. U View dan hodisalarni qabul qiladi va View ga nima qilishni buyuradi.
MVC vs MVP: Farqi nimada?
Section titled “MVC vs MVP: Farqi nimada?”MVC da Controller Model ni yangilaydi, lekin View ba’zan to’g’ridan-to’g’ri Model dan o’zgarishlarni tinglashi mumkin.
MVP da esa View va Model bir-birini mutlaqo bilmaydi. Barcha aloqa Presenter orqali o’tadi.
graph TD View <-->|User Events / Commands| Presenter Presenter <-->|Get/Set Data| Model- View faqat interfeysni chizadi va
Presenterga “tugma bosildi” deb xabar beradi. - Presenter biznes logikani bajaradi va
Viewga “matnni o’zgartir” yoki “xabarni ko’rsat” deb buyruq beradi.
Afzalliklari
Section titled “Afzalliklari”Kamchiliklari
Section titled “Kamchiliklari”Amaliy Misol (Vanilla JS)
Section titled “Amaliy Misol (Vanilla JS)”// View Interfaceclass TodoView { constructor(presenter) { this.presenter = presenter; this.input = document.getElementById("todo-input"); this.list = document.getElementById("todo-list"); document.getElementById("add-btn").onclick = () => this.presenter.onAddClick(); }
getInputValue() { return this.input.value; }
showTodos(todos) { this.list.innerHTML = todos.map((t) => `<li>${t}</li>`).join(""); }
clearInput() { this.input.value = ""; }}
// Presenterclass TodoPresenter { constructor(model) { this.model = model; this.view = null; }
setView(view) { this.view = view; }
onAddClick() { const text = this.view.getInputValue(); if (text) { this.model.add(text); this.view.showTodos(this.model.getAll()); this.view.clearInput(); } }}
// Modelclass TodoModel { constructor() { this.todos = []; } add(text) { this.todos.push(text); } getAll() { return this.todos; }}
// Ishga tushirishconst model = new TodoModel();const presenter = new TodoPresenter(model);const view = new TodoView(presenter);presenter.setView(view);