-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathko-require.js
103 lines (83 loc) · 3.09 KB
/
ko-require.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
define(["knockout", "require"], function (ko, require) {
"use strict";
var KO_REQUIRE_ORIGINAL_VISIBILITY_ATTRIBUTE = "ko-require--original-visibility";
function hideChildNodes (element) {
var child = ko.virtualElements.firstChild(element),
result = [];
while (child) {
if (child.nodeType === window.Node.ELEMENT_NODE) {
child.setAttribute(KO_REQUIRE_ORIGINAL_VISIBILITY_ATTRIBUTE, child.style.visibility);
child.style.visibility = "hidden";
result.push(child);
}
child = ko.virtualElements.nextSibling(child);
}
return result;
}
function showNodes (nodes) {
var node = nodes.shift();
while (node) {
node.style.visibility = node.getAttribute(KO_REQUIRE_ORIGINAL_VISIBILITY_ATTRIBUTE);
node.removeAttribute(KO_REQUIRE_ORIGINAL_VISIBILITY_ATTRIBUTE);
node = nodes.shift();
}
}
function appendNamedTemplate (name, html, element) {
var script;
if (document.getElementById(name) === null) {
script = document.createElement("script");
script.setAttribute("type", "text/html");
script.setAttribute("id", name);
script.innerHTML = html;
ko.virtualElements.prepend(element, script);
}
}
function parseTemplatePath (path) {
var segments = path.split(":");
return {
name: segments[0],
path: "text!" + segments[1]
};
}
function load (options, element, bindingContext) {
var children = hideChildNodes(element),
templateCount = options.templates.length,
templates = options.templates.map(parseTemplatePath),
modules = templates.map(function (template) {
return template.path;
}).concat(options.components);
require(modules, function () {
var argName, index;
for (argName in arguments) {
if (arguments.hasOwnProperty(argName)) {
index = parseInt(argName);
if (arguments.hasOwnProperty(argName) && index < templateCount) {
appendNamedTemplate(templates[index].name, arguments[argName], element);
}
}
}
showNodes(children);
ko.applyBindingsToDescendants(bindingContext, element);
});
}
function update (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = valueAccessor();
if (options.components instanceof Array === false) {
options.components = [];
}
if (options.templates instanceof Array === false) {
options.templates = [];
}
load(options, element, bindingContext);
}
function init () {
return {
controlsDescendantBindings: true
};
}
ko.bindingHandlers.require = {
init: init,
update: update
};
ko.virtualElements.allowedBindings.require = true;
});