MVC in Javascript

时间:2024-10-15 13:05:26

MVC in Javascript

From

http://www.cnblogs.com/tugenhua0707/p/5156179.html

原博的比我详细 我是以自己的惯用的方式实现了一下

MVC就是各尽自己的职责,整个视图都是按照数据来渲染的, 视图本身并不保存数据。 发生的事件由Controller控制, Controller也是修改Model中的数据, 之后调用View中的refreshDOM刷新DOM


var doc = document;
var PubSub = function(){
this.event = [];
}
PubSub.prototype = {
registerEvent: function(fn){
this.event.push(fn);
},
triggerEvent: function(){
this.event.forEach(function(fn){
fn.call(this);
}.bind(this));
}
} var Model = function(list){
this.list = list;
this.addEvent = new PubSub();
this.delEvent = new PubSub();
}
Model.prototype = {
addItem: function(item){
if(item){
this.list.push(item);
}else{
var lastData = self.model.list[self.model.list.length-1];
var num = +lastData.match(/item(\d)/)[1];
this.list.push('item'+(num+1));
}
},
removeItem: function(index){
this.list.splice(index,1);
}
}
var View = function(model,container){
var self = this;
this.model = model;
this.container = container;
this.model.addEvent.registerEvent(function(){
self.model.addItem();
self.refreshDOM();
});
this.model.delEvent.registerEvent(function(){
if(self.container.selectedIndex != -1){
self.model.removeItem(self.container.selectedIndex);
self.refreshDOM();
}
});
this.refreshDOM = function(){
var listData = this.model.list;
var selectElem = doc.querySelector('#list');
selectElem.innerHTML = '';
listData.forEach(function(item){
var option = doc.createElement('option');
option.value = item;
option.innerHTML = item;
self.container.appendChild(option);
});
}
}
var Controller = function(elements, model){
var self = this;
this.addButton = elements.addButton;
this.delButton = elements.delButton;
this.model = model;
this.addButton.addEventListener('click', function(){
self.model.addEvent.triggerEvent();
});
this.delButton.addEventListener('click', function(){
self.model.delEvent.triggerEvent();
})
}
var model = new Model(['item1','item2']);
var view = new View(model, doc.querySelector('#list'));
view.refreshDOM();
var controller = new Controller({
addButton: doc.querySelector('#addBtn'),
delButton: doc.querySelector('#delBtn')
},model)