DIV CSS 佈局教程網

用不到 150 行打造極簡 JavaScript MVC 框架
編輯:關於JavaScript     

Angular、Backbone、Ember 這些框架都很好,但有時候你只需要「點連結換內容」這麼一件小事。為此載入幾百 KB 的框架顯得不划算。本文實作一個極簡的 MVC:用 URL hash 做路由、用 AJAX 載入視圖片段、用簡單的佔位符替換把模型綁進視圖。

設計約定

先把規則定清楚,實作就會很單純:

  • URL 形如 index.html#/home,hash 決定要載入哪個視圖
  • 視圖是外部 HTML 檔,內容用 {{PropertyName}} 標記要填入模型的位置
  • 頁面中有一個帶 view 屬性的元素作為掛載點
  • 每個路由對應一個控制器函式,負責產生模型物件

核心結構

;(function (w, d) {
  'use strict';

  let viewElement = null;
  let defaultRoute = null;

  // 路由資料:控制器 / 路徑 / 視圖檔
  function Route(controller, name, template) {
    this.controller = controller;
    this.name = name;
    this.template = template;
  }

  function JsMvc() {
    this.routes = {};
  }

  // 註冊路由
  JsMvc.prototype.addRoute = function (controller, name, template) {
    this.routes[name] = new Route(controller, name, template);
  };

  // 啟動
  JsMvc.prototype.init = function () {
    viewElement = d.querySelector('[view]');
    if (!viewElement) return;

    const firstKey = Object.keys(this.routes)[0];
    defaultRoute = this.routes[firstKey];

    w.addEventListener('hashchange', this.start.bind(this));
    this.start();
  };

  // 依 hash 決定要載入哪個視圖
  JsMvc.prototype.start = function () {
    const name = w.location.hash.replace(/^#\/?/, '');
    const route = this.routes[name] || defaultRoute;
    this.loadTemplate(route);
  };

  JsMvc.prototype.loadTemplate = function (route) {
    fetch(route.template)
      .then(res => res.text())
      .then(html => this.render(route, html))
      .catch(err => console.error('載入視圖失敗', err));
  };

  JsMvc.prototype.render = function (route, html) {
    const model = {};
    route.controller(model);            // 控制器填寫模型
    viewElement.innerHTML = this.bind(html, model);
  };

  // 把 {{Key}} 換成 model[key]
  JsMvc.prototype.bind = function (html, model) {
    return html.replace(/\{\{(\w+)\}\}/g, (match, key) =>
      Object.prototype.hasOwnProperty.call(model, key) ? model[key] : match
    );
  };

  w.jsMvc = new JsMvc();

})(window, document);

這裡用 fetch 取代了原版手寫的 XMLHttpRequest 分支判斷,程式碼少了三分之二,也不必再管 IE6 的 ActiveX 分支。

在頁面中使用

<h3>Navigation</h3>
<nav>
  <a href="index.html#/home">Home</a>
  <a href="index.html#/contact">Contact</a>
  <a href="index.html#/admin">Admin</a>
</nav>

<h3>View</h3>
<div view></div>

<script>
  jsMvc.addRoute(HomeController,    'home',    'Views/home.html');
  jsMvc.addRoute(ContactController, 'contact', 'Views/contact.html');
  jsMvc.addRoute(AdminController,   'admin',   'Views/admin.html');
  jsMvc.init();

  function HomeController(model) {
    model.Message = 'Hello World';
  }

  function ContactController(model) {
    model.FirstName = 'John';
    model.LastName  = 'Doe';
    model.Phone     = '555-123456';
  }

  function AdminController(model) {
    model.UserName = 'John';
    model.Password = 'MyPassword';
  }
</script>

對應的視圖檔就非常單薄:

<!-- Views/home.html -->
{{Message}}
<!-- Views/contact.html -->
{{FirstName}} {{LastName}}<br />{{Phone}}
<!-- Views/admin.html -->
<label for="txtUserName">User Name</label>
<input type="text" id="txtUserName" value="{{UserName}}" />

<label for="txtPassword">Password</label>
<input type="password" id="txtPassword" value="{{Password}}" />

運行時的兩個必要條件

必須透過 HTTP 伺服器開啟。用 fetch 讀取本機檔案會被瀏覽器的同源政策擋下,直接雙擊 HTML 是跑不起來的。在本機用 npx serve、python -m http.server 或 IIS/nginx 都可以。

模板中的佔位符要記得轉義。如果 {{Message}} 的值來自使用者輸入,直接塞進 innerHTML 會產生 XSS。這個極簡版刻意保持簡單,正式使用前請補上轉義:

function escapeHtml(str) {
  return String(str).replace(/[&<>"']/g, c => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;',
    '"': '&quot;', "'": '&#39;'
  })[c]);
}

這個教學真正的價值

不是「你可以拿它上 production」——它沒有元件、沒有狀態管理、沒有虛擬 DOM,模板替換也不支援條件與迴圈。它的價值在於把 MVC 三個角色還原到最小:路由決定載入哪個視圖,控制器產生資料,視圖透過佔位符呈現資料。理解這三者的關係之後,你會發現 Angular、Vue 這些框架只是在這個骨架上,逐層加上「資料變動自動重繪」「元件嵌套」「依賴注入」等能力。

換句話說,先手寫一遍極簡版,再去看框架文件,那些原本顯得抽象的術語都會突然有具體對應。這比直接從 npm create 開始要有收穫得多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved