This repository has been archived by the owner on May 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataBindUI.js
99 lines (85 loc) · 2.8 KB
/
DataBindUI.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import DataBind from './DataBind.js'
export default class extends DataBind {
constructor (props) {
super(props)
this.el = props.el
this.eventDispatcher()
}
forEach (arr, callback, scope) {
for (let i = 0; i < arr.length; i++) {
callback.call(scope, arr[i], i)
}
}
strToObj (key, value) {
let object = {}
let result = object
let arr = key.split('.')
for (let i = 0; i < arr.length - 1; i++) {
object = object[arr[i]] = {}
}
object[arr[arr.length - 1]] = value
return result
}
getDataValueFromAttr (obj, keys, curIndex = 0) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (key === keys[curIndex]) {
if (typeof obj[key] === 'object') {
return this.getDataValueFromAttr(obj[key], keys, curIndex + 1)
} else {
return obj[key]
}
}
}
}
}
getEls(el) {
return document.querySelectorAll(el)
}
update () {
super.update(() => {
this.forEach(this.getEls(`${this.el} [data-bind]`), (el) => {
el.textContent = this.getDataValueFromAttr(this.data, el.dataset.bind.split('.'))
})
this.forEach(this.getEls(`${this.el} [data-bind-html]`), (el) => {
el.innerHTML = this.getDataValueFromAttr(this.data, el.dataset.bindHtml.split('.'))
})
this.forEach(this.getEls(`${this.el} [data-model], ${this.el} [data-model-change]`), (el) => {
const modelType = el.dataset.model || el.dataset.modelChange
el.value = this.getDataValueFromAttr(this.data, modelType.split('.'))
})
this.forEach(this.getEls(`${this.el} [data-if]`), (el) => {
let value = ''
if (el.dataset.if.indexOf('!') !== -1) {
el.style.display = this.getDataValueFromAttr(this.data, el.dataset.if.replace('!', '').split('.')) ? 'none' : ''
} else {
el.style.display = this.getDataValueFromAttr(this.data, el.dataset.if.split('.')) ? '' : 'none'
}
})
})
}
eventDispatcher () {
const self = this
const modelFn = function (event) {
const key = this.dataset.model || this.dataset.modelChange
const value = this.value
let obj = self.strToObj(key, value)
self.set(obj)
}
const toggleFn = function (event) {
const key = this.dataset.toggle
const value = self.getDataValueFromAttr(self.data, key.split('.'))
let obj = self.strToObj(key, !value)
self.set(obj)
}
this.forEach(this.getEls(`${this.el} [data-model]`), (el) => {
el.addEventListener('keyup', modelFn)
})
this.forEach(this.getEls(`${this.el} [data-model-change]`), (el) => {
el.addEventListener('change', modelFn)
})
this.forEach(this.getEls(`${this.el} [data-toggle]`), (el) => {
el.addEventListener('click', toggleFn)
})
}
}