-
Notifications
You must be signed in to change notification settings - Fork 0
/
knockout.curly.js
91 lines (71 loc) · 2.89 KB
/
knockout.curly.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
{
function ReplaceNodeWithNodes(pToReplace, pReplacements) {
var parent = pToReplace.parentNode;
for (var i = 0; i < pReplacements.length; i++) {
parent.insertBefore(pReplacements[i], pToReplace);
}
parent.removeChild(pToReplace);
}
function VisitNodes(pNode, pfAction) {
pfAction(pNode);
if (pNode.childNodes) {
for (var i = 0; i < pNode.childNodes.length; i++) {
VisitNodes(pNode.childNodes[i], pfAction);
}
}
}
function ApplyKoBracketBinding(pNode) {
var Node = (pNode != null) ? pNode : document.body;
var ReplacementInfos = [];
VisitNodes(Node, function (node) {
if (node.nodeType != 3) return;
if (node.parentNode != null && node.parentNode.nodeName == "SCRIPT") return;
var ReplacementInfo = ReplaceMatches(node, /{{(.*?)}}/, function (Matches) {
var Name = Matches[1];
var node = document.createElement("span");
node.setAttribute("data-bind", "text:" + Name);
return node;
});
if (ReplacementInfo != null) {
ReplacementInfos.push(ReplacementInfo);
}
});
for (var i = 0; i < ReplacementInfos.length; i++) {
var ReplacementInfo = ReplacementInfos[i];
ReplaceNodeWithNodes(ReplacementInfo.ToReplace, ReplacementInfo.Replacements);
}
}
function GetText(node) {
if (node.textContent) return node.textContent;
return node.nodeValue;
}
function ReplaceMatches(pTestNode, pRegEx, pfReplacementNode) {
if (pTestNode.nodeType != 3) throw "This only works on text nodes";
var parent = pTestNode.parentNode;
var Text = GetText(pTestNode);
var NewNodes = [];
var RemainingText = Text;
while (true) {
var IndexOfMatch = RemainingText.search(pRegEx);
if (IndexOfMatch == -1) break;
var Matches = RemainingText.match(pRegEx);
if (IndexOfMatch != 0) {
var BeforePlaceholder = RemainingText.substring(0, IndexOfMatch);
NewNodes.push(document.createTextNode(BeforePlaceholder));
}
NewNodes.push(pfReplacementNode(Matches));
RemainingText = RemainingText.substring(IndexOfMatch + Matches[0].length);
}
if (NewNodes.length == 0) return null;
if (RemainingText.length > 0) {
NewNodes.push(document.createTextNode(RemainingText));
}
return { ToReplace: pTestNode, Replacements: NewNodes };
}
var OriginalApplyBindings = ko.applyBindings;
ko.applyBindings = function (pModel, pNode) {
var Node = (pNode != null) ? pNode : document.body;
ApplyKoBracketBinding(Node);
OriginalApplyBindings(pModel, pNode);
};
}