//Model层
function Model(){
//模拟数据
var val = 0;
//定义一个操作数据的方法跟一个返回数据的方法
this.add = function(){
val +=1;
}
this.getVal = function(){
return val;
}
//观察者模式
var views = []
//将观察者存入数组
this.regist = function(view){
views.push(view);
}
//通知view更新
this.notify = functiong(){
//所有定义了render方法的view都会执行render方法
for(var i = 0;i < views.length;i++){
if(views[i].render){
views[i].render(this);
}
}
}
}
//View层
function View(controller){
//获取节点
var $num = $('#num');
var $add = $('#add');
this.render = function(model){
$num.text(model.getVal());
}
$add.on('click',controller.add)
}
//Controller层
function Controller(){
var model = null;
var view = null;
this.init = function(){
model = new Model();
view = new View(this);
model.regist(view);
}
this.add = function(){
model.add();
model.notify();
}
}
//运行程序时,以Controller为入口
(function(){
var controller = new Controller();
controller.init();
})()