简单的双向绑定实现
2017-05-25 本文已影响15人
mochase
主要是使用到了订阅者模式.
<!--简单的双向绑定实现-->
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<input type="text" data-model="demo">
<p data-bind="demo" class="demo"></p>
<h2 data-bind="demo"></h2>
<span data-bind="demo"></span>
</body>
<script>
//订阅者模式
function Observer() {
this.fns = []
}
Observer.prototype = {
subscribe: function (fn) {
this.fns.push(fn)
},
unsubscribe: function (fn) {
this.fns = this.fns.filter(function(item) {
return item !== fn
})
},
publish: function (data, thisObj) {
var _this = thisObj || this
this.fns.forEach(function(item) {
item.call(_this, data)
})
}
}
var o = new Observer
var subscriber = function (data) {
var i = document.querySelectorAll('*[data-bind="demo"]').length
while (i--) {
document.querySelectorAll('*[data-bind="demo"]')[i].innerHTML = data
}
}
o.subscribe(subscriber)
document.querySelector('*[data-model="demo"]').addEventListener('input', function(e) {
e.preventDefault()
o.publish(document.querySelector('*[data-model="demo"]').value)
})
</script>
</html>
这里订阅者模式还可以完善,引入"话题"参数,使得订阅者可以订阅不同的"话题",对应到双向绑定demo中,监听多处data-model