前端MVC模式

由来:应用复杂性的提高,程序变得臃肿,难以分工开发。通过关注点分离改进程序组织。

前端MVC模式
简单实现:
index.html

<!DOCTYPE html>
<!-- saved from url=(0046)https://coding.imweb.io/demo/p7/mvc/index.html -->
<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .num {
      width: 400px;
      text-align: center;
      line-height: 240px;
      font-size: 60px;
      background: #f4f3f3;
    }

    button {
      width: 200px;
      background: #c15e00;
      color: #fff;
      font-size: 60px;
      border: none;
    }

    .js-sub {
      background: #454242;
      margin-left: -5px
    }
  </style>
</head>

<body>
  <div id="calculator">
    <div class="num">0元</div>
    <button class="js-add">+</button>
    <button class="js-sub">-</button>
  </div>
  <script src="https://7.url.cn/edu/jslib/jquery/1.9.1/jquery.min.js"></script>
  <script src="./js/app.js"></script>

</body>

</html>

app.js

/**
 * Model 模型
 */
function Model() {
  var val = 0;
  // 增加数据
  this.add = function (v) {
    if (val < 100) {
      val += v;
    }
  };
  // 减少数据
  this.sub = function (v) {
    if (val > 0) {
      val -= v;
    }
  };
  // 获取数据
  this.getVal = function () {
    return val;
  };
  /**
   * 观察者模式
   */
  var self = this,
    views = [];

  this.register = function (view) {
    views.push(view);
  };

  this.notify = function () {
    for (var i = 0; i < views.length; i++) {
      views[i].render(self);
    }
  };
};

/**
 * View 视图
 */
function View(controller) {
  var $calculator = $('#calculator');
  var $num = $calculator.find('.num');
  var $addBtn = $calculator.find('.js-add');
  var $subBtn = $calculator.find('.js-sub');

  this.render = function (model) {
    $num.text(model.getVal() + '元');
  };

  /* 绑定事件 */
  $addBtn.click(controller.increase);
  $subBtn.click(controller.decrease);
};

/**
 * Controller 控制器
 */
function Controller() {
  var model = null,
    view = null;

  this.init = function () {
    /* 初始化Model和View */
    model = new Model();
    view = new View(this);

    // View 观察注册 Model,当Model更新就会去通知View啦
    model.register(view);
    model.notify();
  };

  // 让Model更新数值并通知View更新视图 
  this.increase = function () {
    model.add(1);
    model.notify();
  };
  this.decrease = function () {
    model.sub(1);
    model.notify();
  };
};

var controller = new Controller();
controller.init();