MVC

1 MVC基本概念

MVC全名是Model View controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑,数据,界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要从新编写业务逻辑

  1. 逻辑:具体的实际操作
  2. 数据:JSON
  3. 界面:html+css
2 Model模型

定义:提供数据及操作的各种办法
2.1 使用JSON来保存数据
1)JavaScript Object Notation

MVC_第1张图片
1.png

2)创建JSON

  • json有两种典型的样子
    1 - 数组(对象数组,数组中的每一个元素都是对象)
var obj = [
  {"id":"001","name":"Bill","salary":"10k"},
  {"id":"002","name":"George","salary":"12k"},
  {"id":"003","name":"Thomas","salary":"18k"}
]

2 - 对象(就是一个对象)

var stus = {
 "employee" [
    {"name":"Bill","salary":"10k"},
    {"name":"George","salary":"12k"},
    {"name":"Thomas","salary":"18k"}
  ]
}

常见的注意事项:

  • json中的对象,键和值都要加双引号(" ")//不能是单引号
  • 数据在键/值中
  • 数据之间用逗号隔开
  • 花括号中保存对象
  • 方括号保存数组
  • 值可以是(数字/字符串/逻辑值/数组/对象/null)

2.2 如何使用json

  1. 访问单个的json
    ※与访问对象的属性值完全一样(注:需要事先知道json内部结构)
var json = {
  "boss" : {"name":"jack","address":"tina"},
  "employee":[
      {"name":"chengyi1","age":"unkown"},
      {"name":"chengyi2","age":"unkown"},
      {"name":"chengyi3","age":"unkown"}
      ],
"other":null
}
console.info(json2.boss.name);//jack
console.info(json2["boss"]["name"]);//jack
console.info(json2["boss"].name);//jack
console.info(json2.boss["name"]);//jack

2)遍历

var json = {
  "boss" : {"name":"jack","address":"tina"},
  "employee":[
      {"name":"chengyi1","age":"unkown","tel":"12345671324"},
      {"name":"chengyi2","age":"unkown","tel":"12345671324"},
      {"name":"chengyi3","age":"unkown","tel":"12345671324"}
      ],
"other":null
}
for(var p in json2.employee){
console.info(p,json2.employee[p]);

3)添加数据

    1. 如果是数据-使用push的方法
  • 2)如果是对象-对象.new 属性 = 属性值

4)删除数据

    1. 删除对象的属性 delete
      ※不能删除数组指定的下标元素
      ※对于数组json来说,只是第index元素的内容被清空了,然而整个数组的长度(元素的个数)是不会发生改变的
var newGoods = {"id":"4","name":"chengyi"};
delete newGoods.id;
console.info(newGoods);//name:"chengyi"

4.1)删除数组元素(splice)

function deleteById(id,json){
  var index = -1;
  for(var i=0, i

4.2)修改

var json1 = [
 {"id":"1","href":"https://fxhh.jd.com","info":"商品1","img":"img1.png"},
 {"id":"2","href":"https://fxhh.jd.com","info":"商品2","img":"img2.png"},
 {"id":"3","href":"https://fxhh.ti.com","info":"商品3","img":"img3.png"}
]
json1[1].img = "img20.png";

5 把Model封装成字面量对象

var MVC = { };
MVC.model = {
  data:[
    {"id":"1","href":"https://fxhh.jd.com#166791","info":"商品1"},
    {"id":"2","href":"https://fxhh.jd.com#166792","info":"商品2"},
    {"id":"3","href":"https://fxhh.jd.com#166793","info":"商品3"},
  ],
add:function(id,href,info){
   var boj = {
    "id":id,
    "href""href,
    "info":info
  };
  this.data.push(obj);
  }
};
console.info(MVC.model.data);
MVC.model.add(4,"www.baidu.com","百度","img20.png");

※注:add属性值里面不要写双引号,它是函数的局部变量,是一个形参

3 View视图

定义:网页中一块区域的样式呈现
3.1 :template(模板)
3.2 :模块的添加
3.3 :获取数据并且插入到结构中去

4 controller控制器
组件

所谓组件,其实就是具备独立功能的一个模块(UI部件)

你可能感兴趣的:(MVC)