一、MVC概念
MVC是一种架构模式,将应用抽象为3个部分:模型(数据)、视图、用户交互层(控制器)。
事件发生的过程是:
①用户与应用发生交互
②控制器的事件处理器被触发
③控制器从模型中请求数据,并将其交给视图
④视图将数据呈现给用户
1.M-Model,
数据模型,用来存放应用的所有数据对象。模型不用知道视图和控制器的细节,只需要包含数据及直接和这些数据相关的逻辑
2.V-view
视图负责所有UI界面,是呈现给用户的,用户与之交互。在JavaScript中,视图大多数由HTML、CSS和JavaScript模板组成。除了模板中简单的条件语句外,视图不应当包含其他逻辑。
3.C-control
控制器是模型和视图之间的纽带。它从视图中获得事件和输入,怼他们进行处理,并相应地更新视图。当页面加载时,控制器会给视图添加事件监听,比如按钮点击或表单提交。当洪湖和应用发生交互时,控制器中的事件触发器就开始工作。
二、代码说明
//model
const m={
data:{初始化数据}
create(){增},
delete(){删},
update(){改},
get(){查}
}
//view
const v={
el:null,
//初始化html
html:`代码`,
init(container){
v.el=$(container)
},
render(n){}
}
//controller
const c={
init(container){}
},
event:{事件},
add(){执行},
autoBindEvents(){逻辑}
}
}
三、EventtBus
用于模块间的通讯 基本api有
on监听事件,trigger触发事件,off取消监听方法
//EventBus.j代码
class EventBus{
constructor(){
this._eventBus =$(window)
}
on(eventName, fn){
return this._eventBus.on(eventName,fn)
}
trigger(eventName,data){
return this._trigger.tiggger(eventName,data)
}
off(eventName, fn){
return this._eventBus.off(eventName,fn)
}
}
export default EventBus
//new.js代码
import EventBus from 'EventBus.js'
const e =new EventBus()
四、表驱动编程
表驱动方法(Table-Driven Approach)是一种使你可以在表中查找信息,而不必用很多的逻辑语句(if或case)来把它们找出来的方法。
1.在数组中的应用
//if else
function iGetMonthDays(iMonth) {
let iDays;
if(1 == iMonth) {iDays = 31;}
else if(2 == iMonth) {iDays = 28;}
else if(3 == iMonth) {iDays = 31;}
else if(4 == iMonth) {iDays = 30;}
else if(5 == iMonth) {iDays = 31;}
else if(6 == iMonth) {iDays = 30;}
else if(7 == iMonth) {iDays = 31;}
else if(8 == iMonth) {iDays = 31;}
else if(9 == iMonth) {iDays = 30;}
else if(10 == iMonth) {iDays = 31;}
else if(11 == iMonth) {iDays = 30;}
else if(12 == iMonth) {iDays = 31;}
return iDays;
}
//使用表驱动
const monthDays = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
]
function getMonthDays(month, year) {
let isLeapYear = (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0) ? 1 : 0
return monthDays[isLeapYear][(month - 1)];
}
console.log(getMonthDays(2, 2000))
2.对象中的应用
if (key = "Key A")
{
处理 Key A 相关的数据。
}
else if (key = "Key B")
{
处理 Key B 相关的数据。
}
//可以改装成
let table = {
A: {
data: "数据1",
action: "行为1"
},
B: {
data: "数据2",
action: "行为2"
}
}
function handleTable(key) {
return table[key]
}
console.log(handleTable('A').data)
//或者
let table = {
A: {
data: "数据1",
action () {
console.log('action 1')
}
},
B: {
data: "数据2",
action () {
console.log('action 2')
}
}
}
function handleTable(key) {
return table[key]
}
handleTable('A').action()
四、模块化
在js中,实现某个功能后,该功能在其他地方也需要用到,则可以把这个功能看成一个模块采用一定的方式进行编写,这样可以实现复用也可以分而治之;对于css也是一样。