-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathref.js
62 lines (56 loc) · 1.15 KB
/
ref.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* author www.dojs.com
* github: www.github.com/chengse66/ref
* ref like vue.js
*/
class RefObject extends EventTarget{
constructor() {
super();
this._detail = {
prev:null,
now:null
};
this._handle = new CustomEvent("change", {
detail: this._detail,
bubbles: false,
cancelable: true,
});
this._prev = null;
this._value = null;
}
get value() {
return this._value;
}
set value(any) {
this._prev = this._value;
this._value = any;
if (this._prev != this._value) {
this.update();
}
}
update() {
//回调事件
this._detail.prev=this._prev;
this._detail.now=this._value;
this.dispatchEvent(this._handle);
}
/**
*
* @param {(any,any)=>void} callback
* @returns
*/
watch(callback){
const on_change=e=>{
callback(e.detail.now,e.detail.prev);
};
this.addEventListener('change',on_change);
return ()=>{
this.removeEventListener('change',on_change);
};
}
}
const ref = (any) => {
var r=new RefObject();
r.value=any;
return r;
};