Skip to content

Commit 22ab790

Browse files
committed
first commit
0 parents  commit 22ab790

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
function DataBinder(object_id){
3+
let pubSub = {
4+
5+
callbacks:{},
6+
7+
on:function(msg,callback){
8+
if(!this.callbacks[msg]) this.callbacks[msg] = [];
9+
this.callbacks[msg].push(callback);
10+
},
11+
12+
publish:function(msg){
13+
let functionList = this.callbacks[msg];
14+
if(!functionList) return;
15+
functionList.forEach(f => {
16+
f.apply(this,arguments);
17+
})
18+
}
19+
20+
}
21+
22+
let key = 'bind-' + object_id;
23+
let msg = 'change:' + object_id;
24+
25+
document.addEventListener('input',event =>{
26+
let tgt = event.target;
27+
let prop_name = tgt.getAttribute(key);
28+
if(prop_name && prop_name!='')
29+
//prop_name表示绑定object_id对象的哪个属性
30+
pubSub.publish(msg,prop_name,tgt.value);
31+
})
32+
33+
pubSub.on(msg,(_,prop_name,new_val) => {
34+
let doms = document.querySelectorAll("[" + key + "=" + prop_name + "]"),tag_name;
35+
for(let dom of doms)
36+
{
37+
tag_name = dom.tagName.toLowerCase();
38+
if(tag_name == 'select' || tag_name == 'input' || tag_name == 'textarea')
39+
dom.value = new_val;
40+
else
41+
dom.innerHTML = new_val;
42+
}
43+
})
44+
45+
return pubSub;
46+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title></title>
5+
</head>
6+
<body>
7+
<input bind-xx = 'aaa'></input>
8+
<br>
9+
<br>
10+
<br>
11+
<textarea bind-xx = 'aaa'></textarea>
12+
</body>
13+
<script src="./DataBinder.js"></script>
14+
<script type="text/javascript">
15+
function User(user_id){
16+
let binder = new DataBinder(user_id);
17+
let user = {
18+
19+
attributes: {},
20+
21+
set:function(prop_name,val){
22+
this.attributes[prop_name] = val;
23+
binder.publish("change:"+user_id,prop_name,val,this);
24+
},
25+
get:function(prop_name){
26+
return this.attributes[prop_name];
27+
}
28+
29+
}
30+
31+
binder.on("change:"+user_id,(_,prop_name,val,init) => {
32+
if(init != user) //避免循环调用
33+
user.set(prop_name,val)
34+
})
35+
36+
return user;
37+
38+
}
39+
let user = new User('xx');
40+
setTimeout(()=>user.set('aaa','re'),3000);
41+
42+
</script>
43+
</html>

0 commit comments

Comments
 (0)