-
Notifications
You must be signed in to change notification settings - Fork 6
/
objectbinding.go
69 lines (52 loc) · 1.11 KB
/
objectbinding.go
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
63
64
65
66
67
68
69
package obsfx
type ObjectBinding[T, V any] struct {
ObservableValueBase[V]
src ObservableValue[T]
mapper func(T) V
value V
valid bool
}
func NewObjectBinding[T, V any](src ObservableValue[T], mapper func(T) V) *ObjectBinding[T, V] {
ob := &ObjectBinding[T, V]{
src: src,
mapper: mapper,
}
src.AddListener(ob)
return ob
}
func (b *ObjectBinding[T, V]) Dependencies() []Observable {
return []Observable{b.src}
}
func (b *ObjectBinding[T, V]) Invalidate() {
b.markInvalid()
}
func (b *ObjectBinding[T, V]) IsValid() bool {
return b.valid
}
func (o *ObjectBinding[T, V]) RawValue() any {
return o.Value()
}
func (b *ObjectBinding[T, V]) Value() V {
if !b.valid {
b.value = b.mapper(b.src.Value())
b.valid = true
}
return b.value
}
func (b *ObjectBinding[T, V]) OnInvalidated(prop Observable) {
b.markInvalid()
}
func (b *ObjectBinding[T, V]) Close() {
for _, dep := range b.Dependencies() {
dep.RemoveListener(b)
}
}
func (b *ObjectBinding[T, V]) markInvalid() {
if b.valid {
b.valid = false
b.ObservableValueBase.OnInvalidated(b)
if !b.valid {
b.value = EmptyValue[V]()
}
}
}