js實現資料繫結
阿新 • • 發佈:2019-01-27
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>data-binding-method-set</title>
</head>
<body>
<input q-value="value" type="text" id="input">
<div q-text="value" id="el"></div>
<script>
var elems = [document.getElementById('el'), document.getElementById('input')];
var data = {
value: 'hello!'
};
var command = {
text: function(str){
this.innerHTML = str;
},
value: function(str){
this.setAttribute('value', str);
}
};
var scan = function(){
/**
* 掃描帶指令的節點屬性
*/
for(var i = 0, len = elems.length; i < len; i++){
var elem = elems[i];
elem.command = [];
for(var j = 0, len1 = elem.attributes.length; j < len1; j++){
var attr = elem.attributes[j];
if(attr.nodeName.indexOf('q-') >= 0){
/**
* 呼叫屬性指令,這裡可以使用資料改變檢測
*/
command[attr.nodeName.slice(2)].call(elem, data[attr.nodeValue]);
elem.command.push(attr.nodeName.slice(2));
}
}
}
}
/**
* 設定資料後掃描
*/
function mvSet(key, value){
data[key] = value;
scan();
}
/**
* 資料繫結監聽
*/
elems[1].addEventListener('keyup', function(e){
mvSet('value', e.target.value);
}, false);
scan();
/**
* 改變資料更新檢視
*/
setTimeout(function(){
mvSet('value', 'fuck');
},1000)
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>data-binding-method-set</title>
</head>
<body>
<input q-value="value" type="text" id="input">
<div q-text="value" id="el"></div>
<script>
var elems = [document.getElementById('el'), document.getElementById('input')];
var data = {
value: 'hello!'
};
var command = {
text: function(str){
this.innerHTML = str;
},
value: function(str){
this.setAttribute('value', str);
}
};
var scan = function(){
/**
* 掃描帶指令的節點屬性
*/
for(var i = 0, len = elems.length; i < len; i++){
var elem = elems[i];
elem.command = [];
for(var j = 0, len1 = elem.attributes.length; j < len1; j++){
var attr = elem.attributes[j];
if(attr.nodeName.indexOf('q-') >= 0){
/**
* 呼叫屬性指令,這裡可以使用資料改變檢測
*/
command[attr.nodeName.slice(2)].call(elem, data[attr.nodeValue]);
elem.command.push(attr.nodeName.slice(2));
}
}
}
}
/**
* 設定資料後掃描
*/
function mvSet(key, value){
data[key] = value;
scan();
}
/**
* 資料繫結監聽
*/
elems[1].addEventListener('keyup', function(e){
mvSet('value', e.target.value);
}, false);
scan();
/**
* 改變資料更新檢視
*/
setTimeout(function(){
mvSet('value', 'fuck');
},1000)
</script>
</body>
</html>