# MVC 模式

MVC 即模型(Model)-视图(View)-控制器(Controller),用一种将业务逻辑、数据、视图分离的方式组织架构代码。

# 分层思想

MVC 是用来分层的,我们对页面处理也是更具 MVC 的思想,将页面分成 3 层部分,数据层部分、视图层部分、控制器层部分。

视图层可以调用数据层创建视图,控制器层可以调用数据层数据与视图层内的视图创建页面增添逻辑。

// MVC.js
$(function(){
  // 初始化 MVC 对象
  const MVC = MVC || {};
  // 初始化数据模型层
  MVC.model = function(){}();
  // 初始化视图层
  MVC.view = function(){}();
  // 初始化控制器
  MVC.ctrl = function(){}();
})

# 数据层

MVC.model = (function () {
  const M = {};
  M.data = {};
  M.conf = {};
  return {
    getData: function (k) {
      return M.data[k];
    },
    getConf: function (c) {
      return M.conf[c];
    },
    setData: function (k, v) {
      M.data[k] = v;
      return this;
    },
    setConf:function(c,v){
      M.data[c] = v;
      return this;
    }
  };
})();

# 视图层

MVC.view = (function () {
  const M = MVC.model;
  const V = {};
  return function (v) {
    V[v]();
  };
})();

# 控制器层

MVC.ctrl = (function () {
  const M = MVC.model;
  const V = MVC.view;
  const C = {};
})();

# 实现一个侧边导航栏

// ...
M.data = {
  slideBar: [
    { text: "番剧", href: "https://www.bilibili.com/anime/" },
    { text: "国创", href: "https://www.bilibili.com/guochuang/" },
    { text: "电影", href: "https://www.bilibili.com/movie/" },
    { text: "电视剧", href: "https://www.bilibili.com/tv/" },
    { text: "纪录片", href: "https://www.bilibili.com/documentary/" },
    { text: "动画", href: "https://www.bilibili.com/v/douga/" },
    { text: "科技", href: "https://www.bilibili.com/v/tech/" },
    { text: "游戏", href: "https://www.bilibili.com/v/game/" },
    { text: "音乐", href: "https://www.bilibili.com/v/music/" },
    { text: "知识", href: "https://www.bilibili.com/v/knowledge/" }
  ]
};
M.conf = {
  slideBarCloseAnimate: false
};
// ...
// ...
const V = {
  createSlideBar: function () {
    let html = "";
    const data = M.getData("slideBar");
    if (!data || !data.length) {
      return false;
    }
    const dom = $.create("div", {
      class: "slidebar",
      id: "clidebar"
    });
    const template = {
      container: `
      <div class="slidebar-inner"><ul>{#content#}</ul></div>
      <a class="slidebar-close" hidefocus href="#" title="收起"></a>
      `,
      item: `
      <li>
        <a class="icon" href="{#href#}">
          <img src="common/img/{#icon#}">
          <span>{#text#}</span>
        </a>
        <div class="box">
          <div>
            <a class="title" href="{#href#}" >{#title#}</a>
            <a href="{#href#}">{#content#}</a>
          </div>
          <a class="image" href="{#href#}">
            <img src="common/img/{#img#}"/>
          </a>
        </div>
      </li>
      `
    };
    for (let i = 0; i < data.length; i++) {
      html += $.formateString(template.item, data[i]);
    }
    dom.html($.formateString(template.container, { content: html })).appendTo("body");
  }
};
// ...