-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata-bind.js
More file actions
66 lines (53 loc) · 1.54 KB
/
data-bind.js
File metadata and controls
66 lines (53 loc) · 1.54 KB
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
export class Model {
/**
* Instantiate a data binding model.
* @param {string?} name optional model name
*/
constructor(name) {
this.name = name
this.history = {}
this.subscribers = {}
}
/**
* Establish a one-way data binding from the model's "fromProp" property to "toObj"'s "toProp" property.
* @param {string} fromProp
* @param {object} toObj
* @param {string} toProp
*/
bind(fromProp, toObj, toProp) {
checkInput()
const model = this
registerNewSubscriber()
initPropertyHistory()
registerPropertySetter()
function checkInput() {
if (!fromProp instanceof String)
throw new Error('fromProp must be string')
if (!toObj instanceof Object)
throw new Error('toObj must be object')
if (!toProp instanceof String)
throw new Error('toProp must be string')
}
function registerNewSubscriber() {
if (!model.subscribers[fromProp])
model.subscribers[fromProp] = []
model.subscribers[fromProp].push([toObj, toProp])
}
function initPropertyHistory() {
if (!model.history[fromProp])
model.history[fromProp] = []
}
function registerPropertySetter() {
if (model.hasOwnProperty(fromProp))
return
Object.defineProperty(model, fromProp, {
set: function(val) {
model.history[fromProp].push(val)
model.subscribers[fromProp].forEach(([obj, prop]) => {
obj[prop] = val
})
}
})
}
}
}