forked from featurist/hyperdom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapBinding.js
111 lines (98 loc) · 2.58 KB
/
mapBinding.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
100
101
102
103
104
105
106
107
108
109
110
111
var bindingMeta = require('./meta')
function makeConverter (converter) {
if (typeof converter === 'function') {
return {
view: function (model) {
return model
},
model: function (view) {
return converter(view)
}
}
} else {
return converter
}
}
function chainConverters (startIndex, converters) {
function makeConverters () {
if (!_converters) {
_converters = new Array(converters.length - startIndex)
for (var n = startIndex; n < converters.length; n++) {
_converters[n - startIndex] = makeConverter(converters[n])
}
}
}
if ((converters.length - startIndex) === 1) {
return makeConverter(converters[startIndex])
} else {
var _converters
return {
view: function (model) {
makeConverters()
var intermediateValue = model
for (var n = 0; n < _converters.length; n++) {
intermediateValue = _converters[n].view(intermediateValue)
}
return intermediateValue
},
model: function (view) {
makeConverters()
var intermediateValue = view
for (var n = _converters.length - 1; n >= 0; n--) {
intermediateValue = _converters[n].model(intermediateValue)
}
return intermediateValue
}
}
}
}
module.exports = function (model, property) {
var _meta
function hyperdomMeta () {
return _meta || (_meta = bindingMeta(model, property))
}
var converter = chainConverters(2, arguments)
return {
get: function () {
var meta = hyperdomMeta()
var modelValue = model[property]
var modelText
if (meta.error) {
return meta.view
} else if (meta.view === undefined) {
modelText = converter.view(modelValue)
meta.view = modelText
return modelText
} else {
var previousValue
try {
previousValue = converter.model(meta.view)
} catch (e) {
meta.error = e
return meta.view
}
modelText = converter.view(modelValue)
var normalisedPreviousText = converter.view(previousValue)
if (modelText === normalisedPreviousText) {
return meta.view
} else {
meta.view = modelText
return modelText
}
}
},
set: function (view) {
var meta = hyperdomMeta()
meta.view = view
try {
model[property] = converter.model(view, model[property])
delete meta.error
} catch (e) {
meta.error = e
}
},
meta: function () {
return hyperdomMeta()
}
}
}