<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
订阅视图 - 1:<span class="box-1">11</span><br />
订阅视图 - 2:<span class="box-2">22</span><br />
</div>
<script>
//订阅器模型
let Dep = {
//储存
clientList: {},
listen: function(key, fn) {
(this.clientList[key] || (this.clientList[key] = [])).push(fn)
},
trigger: function() {
let key = Array.prototype.slice.call(arguments),
fns = this.clientList[key]
if (!fns || fns.length === 0) {
return false
}
for (let i = 0, fn; fn = fns[i++];) {
fn.apply(this, arguments)
}
}
}
//劫持方法
let dataHijack = function({ data, tag, datakey, selector }) {
let value = "",
el = document.querySelector(selector);
Object.defineProperty(data, datakey, {
get: function() {
console.log('获取值')
return value
},
set: function(newValue) {
console.log('设置值')
value = newValue
Dep.trigger(tag, newValue)
}
});
//订阅数组
Dep.listen(tag, function(text) {
el.innerHtml = text
})
}
//调用以上方法
let dataObj = {};
dataHijack({
data: dataObj,
tag: 'view-1',
datakey: "one",
selector: ".box-1"
})
dataHijack({
data: dataObj,
tag: 'view-2',
datakey: "two",
selector: ".box-2"
})
dataObj.one = "one one one "
dataObj.two = "two two "
</script>
</body>
</html>
网友评论