关于MVC的理解
程序员文章站
2022-03-06 08:07:20
...
先来一个图
非常简易的MVC代码实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MVC架构理解2</title>
</head>
<body>
<div id="div1" bind="model1">123</div>
<div id="div2" bind="model2">456</div>
</body>
<script type="text/javascript">
window.onload = function () {
/* Model设计 */
function Model (value) {
this._value = typeof value === 'undefined'?'':value;
this._listeners = [];
}
Model.prototype.set = function (value) {
var self = this;
self._value = value;
setTimeout(function () {
self._listeners.forEach( function(listener) {
// 改变listener的作用域,并执行listener函数
listener.call(self, value);
});
});
}
Model.prototype.watch = function (listener) {
this._listeners.push(listener);
}
Model.prototype.bind = function (node) {
this.watch(function (value) {
node.innerHTML = value;
});
}
/* Controller设计 */
function Controller (callback) {
var models = {};
var views = document.querySelectorAll('[bind]');
views = Array.prototype.slice.call(views,0);
views.forEach( function(view) {
var modelName = view.getAttribute('bind');
models[modelName] = models[modelName] || new Model();
models[modelName].bind(view);
});
callback.call(this,models);
}
/* 业务代码 */
new Controller(function (models) {
var model1 = models.model1;
model1.set('this is model1');
setTimeout(function () {
model1.set('my name is xxx');
},2000);
});
}
</script>
</html>
代码中可以清楚的看到Controller中主要控制的是Model,Model中主要控制View,至于View触发Controller的内容,本文没有实现
上一篇: python 模拟收银台
下一篇: 扑克牌比较 (Java)