MVC 简介

MVC模式(Model–view–controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller)。

  • Model:处理数据
  • View:处理界面
  • Controller:处理事件,连接 Model 和 View

以下是一个购物清单APP的例子:

示例图
示例图

EventBus API

Event - Web APIs | MDN

何为表驱动编程

A table-driven method is a scheme that allows you to look up information in a table rather than using logic statements (if and case) to figure it out.

表驱动编程就是用数据结构取代逻辑判断语句(例如:if…else),它可用于取代重复但有点不同的代码。我之前写了个鼠标检测网页,一开始用 if 语句判断按钮。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
button.addEventListener("mousedown", logMouseButton);
function logMouseButton(e) {
  if (e.button === 0) {
    log.textContent = "left button";
  } else if (e.button === 1) {
    log.textContent = "middle button";
  } else if (e.button === 2) {
    log.textContent = "right button";
  } else if (e.button === 3) {
    log.textContent = "back button";
  } else if (e.button === 4) {
    log.textContent = "forward button";
  } else {
    log.textContent = `unknown button code: ${e.button}`;
  }
}

然后用表驱动编程,将 if 语句换成了对象:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const buttonPairs = {
  0: "left button",
  1: "middle button",
  2: "right button",
  3: "back button",
  4: "forward button",
};
button.addEventListener("mousedown", (e) => {
  changeColor();
  modifyLog(buttonPairs[e.button]);
});

模块化

模块化编程将不同功能做出不同模块,模块间彼此独立,所以可以单独修改部分模块,而不是牵一发而动全身。

参考资料