30行代码实现Javascript中的MVC
MVC的本质就是在controller中完成业务逻辑,并对model进行修改,同时model的改变引起view的自动更新
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.call(self, value);
});
});
};
Model.prototype.watch =
function
(listener) {
this
._listeners.push(listener);
};
Model.prototype.bind =
function
(node) {
this
.watch(
function
(value) {
node.innerHTML = value;
});
};
function
Controller(callback) {
var
models = {};
var
views = Array.prototype.slice.call(document.querySelectorAll(
'[bind]'
), 0);
views.forEach(
function
(view) {
var
modelName = view.getAttribute(
'bind'
);
(models[modelName] = models[modelName] ||
new
Model()).bind(view);
});
callback.call(
this
, models);
}