Skip to content

Instantly share code, notes, and snippets.

@qzm
Last active June 14, 2019 10:15
Show Gist options
  • Save qzm/dde51b7896cc48e5ed276c9a4e7ec051 to your computer and use it in GitHub Desktop.
Save qzm/dde51b7896cc48e5ed276c9a4e7ec051 to your computer and use it in GitHub Desktop.
mvvm 框架的实现
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>MVVM</title>
<script src="mvvm.js"></script>
</head>
<body>
<div><span>js->dom数据(counter) :</span><input type="text" q-model="counter"></div>
<div><span>js->dom数据(counter) :</span><input type="text" q-model="counter"></div>
<div><span>dom->js->dom数据(hello) :</span><input type="text" q-model="hello"></div>
<div><span>dom->js->dom数据(hello) :</span><input type="text" q-model="hello"></div>
<div><span>dom->js->dom数据(hello) :</span><input type="text" q-model="hello"></div>
<h1 q-model="time"></h1>
<h1 q-model="counter"></h1>
<h1 q-model="hello"></h1>
</body>
</html>
(function (document, window) {
'use strict';
// 需要被绑定的事件
var BIND_EVENT = ['keyup', 'change'];
// 用于存储数据
var database = {
counter: 0,
hello: '',
time: ''
};
// 绑定事件
var setEvent = function () {
BIND_EVENT.map(function (eventName) {
// 闭包存储cache
var cache = ''
document.addEventListener(eventName, function (event) {
if (typeof event.target.value != 'undefined' && cache != event.target.value) {
// 修改绑定的数据
database[event.target.attributes['q-model'].value] = event.target.value;
// 修改缓存
cache = event.target.value;
}
})
});
}
// 设置Property
var setProperty = function (bindModel) {
Object.defineProperty(database, bindModel, {
enumerable: true,
get: function () {
return document.querySelector('[q-model=' + bindModel + ']').value;
},
set: function (newValue) {
// 赋值到Dom
var allBindingElement = document.querySelectorAll('[q-model=' + bindModel + ']');
for (var i = 0; i < allBindingElement.length; i++) {
// 修改value
allBindingElement[i].value = newValue;
// 修改innerText
try {
allBindingElement[i].innerText = newValue;
} catch (err) {}
}
}
});
}
// 遍历,给database的元素添加set,get方法
var bindData = function () {
// 绑定的数据
for (var bindModel in database) {
if (database.hasOwnProperty(bindModel)) {
setProperty(bindModel);
}
}
};
window.onload = function () {
setEvent(); // 给input绑定事件
bindData(); // 绑定数据
// 修改js的值会引起dom节点的更新
var counter = 0;
setInterval(function () {
database.time = (new Date()).toLocaleString();
database.counter++;
}, 1000);
};
}(document, window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment