用原生JS模拟双向绑定
双向绑定
看到angular的双向绑定,想模拟实践下,当然运行效率是硬伤。
angular的双向绑定是通过$watch
实现的,如$scope
的变量都会保存到$$watchers
数组中,然后添加$watch
监听,实现双向绑定。(关于angular的$watch
可自行)
顺便说一句,调试时修改angular里面的变量可以通过angular.element('.myapp').scope().num = 2;
实现,myApp
是ng-app="myApp"
的值。
这里的双向绑定分两步实现,一是从js的变量绑定到dom(也就是显示的html文件),二是从dom绑定到js的变量。
一是从js的变量绑定到dom,修改JS的变量时,dom也会跟着改变。
对一般的Object,可以使用getter和setter实现该效果。(对于Array,可以修改原型实现,这里的实现是参考如何监听 js 中变量的变化?),这里用到的时Object.defineProperty
let scope = {
num: 0
};
//缓存
let watchers = {};
//绑定变量
function watch(scope){
const propertys = Object.keys(scope);
propertys.forEach(function (prop){
//console.log(prop);
//不处理函数属性
if( 'function' == typeof scope[prop] ) return;
const propName = prop;
console.log(propName, scope[prop]);
//监听对象属性
Object.defineProperty(scope, prop, {
configurable: true,
get: function() {
//scope[property]会导致栈溢出,因为一直递归(Uncaught RangeError: Maximum call stack size exceeded)
return watchers[propName];
},
set: function(value) {
//scope[property]会导致栈溢出,因为一直递归(Uncaught RangeError: Maximum call stack size exceeded)
watchers[prop] = value;
document.querySelector("*[ng-bind='"+prop+"']").innerText = watchers[prop];
}
});
});
}
watch(scope);
scope.num = 2; // set:2
console.log(scope.num); // get:2
二是监听dom修改,修改JS变量。这里监听的对象是节点的文本,当文本修改时就修改相应的JS变量
document.addEventListener('DOMCharacterDataModified',element,false);
function element(e){
const attrs = e.target.parentElement.attributes;
for(let i=0; i<attrs.length; i++){
const attr = attrs[i];
if('ng-bind' === attr.nodeName){
console.log('ng-bind', scope[attr.nodeValue]);
scope[attr.nodeValue] = e.newValue;
}
}
}
dom可监听的不同事件类型:https://developer.mozilla.org/zh-CN/docs/Web/Events
DOMAttributeNameChanged
DOMAttrModified
DOMCharacterDataModified
DOMContentLoaded
DOMElementNameChanged
DOMNodeInserted
DOMNodeInsertedIntoDocument
DOMNodeRemoved
DOMNodeRemovedFromDocument
DOMSubtreeModified
综合
整合以上两步,注意watch
函数的代码修改了,代码如下:
//实际数据
let scope = {
num: 0
};
//缓存
let watchers = {};
//绑定从dom到js
document.addEventListener('DOMCharacterDataModified', element,false);
//绑定:从js到dom
watch(scope);
scope.num = 2; // set:2
console.log(scope.num); // get:2
//绑定变量
function watch(scope){
const propertys = Object.keys(scope);
propertys.forEach(function (prop){
//console.log(prop);
//不处理函数属性
if( 'function' == typeof scope[prop] ) return;
const propName = prop;
console.log(propName, scope[prop]);
//监听对象属性
Object.defineProperty(scope, prop, {
//value: scope[prop],
configurable: true,
get: function() {
//scope[property]会导致栈溢出,因为一直递归(Uncaught RangeError: Maximum call stack size exceeded)
//console.log('get', prop, 'for', propName);
return watchers[propName];
},
set: function(value) {
//scope[property]会导致栈溢出,因为一直递归(Uncaught RangeError: Maximum call stack size exceeded)
//console.log('set', prop, 'for', propName);
//防止递归导致的栈溢出,先去掉监听的函数
document.removeEventListener('DOMCharacterDataModified', element);
watchers[prop] = value;
document.querySelector("*[ng-bind='"+prop+"']").innerText = watchers[prop];
//重新监听
document.addEventListener('DOMCharacterDataModified', element,false);
}
});
});
}
//dom的修改触发JS变量的修改
function element(e){
console.log(e.newValue, e.prevValue, e.path);
const attrs = e.target.parentElement.attributes;
for(let i=0; i<attrs.length; i++){
const attr = attrs[i];
if('ng-bind' === attr.nodeName){
console.log('ng-bind', scope[attr.nodeValue]);
scope[attr.nodeValue] = e.newValue;
}
}
}
注意:这里只对调用watch函数是scope已有的属性进行双向绑定,后续往scope添加属性都不会是双向绑定的。
相应的html
<html>
<body>
<h1 ng-bind="num"></h1>
<input id="text"/>
</body>
<script>
//上面的js代码
</script>
<script>
//通过输入框修改变量
document.getElementById('text').oninput = function(e){
const v = document.getElementById("text").value;
const prop = 'num';
document.querySelector("*[ng-bind='"+prop+"']").innerText = v;
}
</script>
</html>