/
utils.js
361 lines (323 loc) · 15.8 KB
/
utils.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/// <reference path="namespace.js" />
ko.utils = new (function () {
var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
var isIe6 = /MSIE 6/i.test(navigator.userAgent);
return {
fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
arrayForEach: function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i]);
},
arrayIndexOf: function (array, item) {
if (typeof array.indexOf == "function")
return array.indexOf(item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] == item)
return i;
return -1;
},
arrayFirst: function (array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++)
if (predicate.call(predicateOwner, array[i]))
return array[i];
return null;
},
arrayRemoveItem: function (array, itemToRemove) {
var index = ko.utils.arrayIndexOf(array, itemToRemove);
if (index >= 0)
array.splice(index, 1);
},
arrayGetDistinctValues: function (array) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++) {
if (ko.utils.arrayIndexOf(result, array[i]) < 0)
result.push(array[i]);
}
return result;
},
arrayMap: function (array, mapping) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
result.push(mapping(array[i]));
return result;
},
arrayFilter: function (array, predicate) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
if (predicate(array[i]))
result.push(array[i]);
return result;
},
arrayPushAll: function (array, valuesToPush) {
for (var i = 0, j = valuesToPush.length; i < j; i++)
array.push(valuesToPush[i]);
},
emptyDomNode: function (domNode) {
while (domNode.firstChild) {
ko.utils.domData.cleanNodeAndDescendants(domNode.firstChild);
domNode.removeChild(domNode.firstChild);
}
},
setDomNodeChildren: function (domNode, childNodes) {
ko.utils.emptyDomNode(domNode);
if (childNodes) {
ko.utils.arrayForEach(childNodes, function (childNode) {
domNode.appendChild(childNode);
});
}
},
replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
if (nodesToReplaceArray.length > 0) {
var insertionPoint = nodesToReplaceArray[0];
var parent = insertionPoint.parentNode;
for (var i = 0, j = newNodesArray.length; i < j; i++)
parent.insertBefore(newNodesArray[i], insertionPoint);
for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
ko.utils.domData.cleanNodeAndDescendants(nodesToReplaceArray[i]);
parent.removeChild(nodesToReplaceArray[i]);
}
}
},
setOptionNodeSelectionState: function (optionNode, isSelected) {
// IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
if (navigator.userAgent.indexOf("MSIE 6") >= 0)
optionNode.setAttribute("selected", isSelected);
else
optionNode.selected = isSelected;
},
getElementsHavingAttribute: function (rootNode, attributeName) {
if ((!rootNode) || (rootNode.nodeType != 1)) return [];
var results = [];
if (rootNode.getAttribute(attributeName) !== null)
results.push(rootNode);
var descendants = rootNode.getElementsByTagName("*");
for (var i = 0, j = descendants.length; i < j; i++)
if (descendants[i].getAttribute(attributeName) !== null)
results.push(descendants[i]);
return results;
},
stringTrim: function (string) {
return (string || "").replace(stringTrimRegex, "");
},
stringTokenize: function (string, delimiter) {
var result = [];
var tokens = (string || "").split(delimiter);
for (var i = 0, j = tokens.length; i < j; i++) {
var trimmed = ko.utils.stringTrim(tokens[i]);
if (trimmed !== "")
result.push(trimmed);
}
return result;
},
stringStartsWith: function (string, startsWith) {
string = string || "";
if (startsWith.length > string.length)
return false;
return string.substring(0, startsWith.length) === startsWith;
},
evalWithinScope: function (expression, scope) {
if (scope === undefined)
return (new Function("return " + expression))();
with (scope) { return eval("(" + expression + ")"); }
},
domNodeIsContainedBy: function (node, containedByNode) {
if (containedByNode.compareDocumentPosition)
return (containedByNode.compareDocumentPosition(node) & 16) == 16;
while (node != null) {
if (node == containedByNode)
return true;
node = node.parentNode;
}
return false;
},
domNodeIsAttachedToDocument: function (node) {
return ko.utils.domNodeIsContainedBy(node, document);
},
registerEventHandler: function (element, eventType, handler) {
if (typeof jQuery != "undefined")
jQuery(element)['bind'](eventType, handler);
else if (typeof element.addEventListener == "function")
element.addEventListener(eventType, handler, false);
else if (typeof element.attachEvent != "undefined")
element.attachEvent("on" + eventType, function (event) {
handler.call(element, event);
});
else
throw new Error("Browser doesn't support addEventListener or attachEvent");
},
triggerEvent: function (element, eventType) {
if (!(element && element.nodeType))
throw new Error("element must be a DOM node when calling triggerEvent");
if (typeof document.createEvent == "function") {
if (typeof element.dispatchEvent == "function") {
var eventCategory = (eventType == "click" ? "MouseEvents" : "HTMLEvents"); // Might need to account for other event names at some point
var event = document.createEvent(eventCategory);
event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
element.dispatchEvent(event);
}
else
throw new Error("The supplied element doesn't support dispatchEvent");
} else if (typeof element.fireEvent != "undefined") {
// Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
// so to make it consistent, we'll do it manually here
if (eventType == "click") {
if ((element.tagName == "INPUT") && ((element.type.toLowerCase() == "checkbox") || (element.type.toLowerCase() == "radio")))
element.checked = element.checked !== true;
}
element.fireEvent("on" + eventType);
}
else
throw new Error("Browser doesn't support triggering events");
},
unwrapObservable: function (value) {
return ko.isObservable(value) ? value() : value;
},
domNodeHasCssClass: function (node, className) {
var currentClassNames = (node.className || "").split(/\s+/);
return ko.utils.arrayIndexOf(currentClassNames, className) >= 0;
},
toggleDomNodeCssClass: function (node, className, shouldHaveClass) {
var hasClass = ko.utils.domNodeHasCssClass(node, className);
if (shouldHaveClass && !hasClass) {
node.className = (node.className || "") + " " + className;
} else if (hasClass && !shouldHaveClass) {
var currentClassNames = (node.className || "").split(/\s+/);
var newClassName = "";
for (var i = 0; i < currentClassNames.length; i++)
if (currentClassNames[i] != className)
newClassName += currentClassNames[i] + " ";
node.className = ko.utils.stringTrim(newClassName);
}
},
range: function (min, max) {
min = ko.utils.unwrapObservable(min);
max = ko.utils.unwrapObservable(max);
var result = [];
for (var i = min; i <= max; i++)
result.push(i);
return result;
},
makeArray: function(arrayLikeObject) {
var result = [];
for (var i = arrayLikeObject.length - 1; i >= 0; i--){
result.push(arrayLikeObject[i]);
};
return result;
},
isIe6 : isIe6,
getFormFields: function(form, fieldName) {
var fields = ko.utils.makeArray(form.getElementsByTagName("INPUT")).concat(ko.utils.makeArray(form.getElementsByTagName("TEXTAREA")));
var isMatchingField = (typeof fieldName == 'string')
? function(field) { return field.name === fieldName }
: function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
var matches = [];
for (var i = fields.length - 1; i >= 0; i--) {
if (isMatchingField(fields[i]))
matches.push(fields[i]);
};
return matches;
},
stringifyJson: function (data) {
if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
return JSON.stringify(ko.utils.unwrapObservable(data));
},
postJson: function (urlOrForm, data, options) {
options = options || {};
var params = options['params'] || {};
var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
var url = urlOrForm;
// If we were given a form, use its 'action' URL and pick out any requested field values
if((typeof urlOrForm == 'object') && (urlOrForm.tagName == "FORM")) {
var originalForm = urlOrForm;
url = originalForm.action;
for (var i = includeFields.length - 1; i >= 0; i--) {
var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
for (var j = fields.length - 1; j >= 0; j--)
params[fields[j].name] = fields[j].value;
}
}
data = ko.utils.unwrapObservable(data);
var form = document.createElement("FORM");
form.style.display = "none";
form.action = url;
form.method = "post";
for (var key in data) {
var input = document.createElement("INPUT");
input.name = key;
input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
form.appendChild(input);
}
for (var key in params) {
var input = document.createElement("INPUT");
input.name = key;
input.value = params[key];
form.appendChild(input);
}
document.body.appendChild(form);
options['submitter'] ? options['submitter'](form) : form.submit();
setTimeout(function () { form.parentNode.removeChild(form); }, 0);
},
domData: {
uniqueId: 0,
dataStoreKeyExpandoPropertyName: "__ko__" + (new Date).getTime(),
dataStore: {},
get: function (node, key) {
var allDataForNode = ko.utils.domData.getAll(node, false);
return allDataForNode === undefined ? undefined : allDataForNode[key];
},
set: function (node, key, value) {
var allDataForNode = ko.utils.domData.getAll(node, true);
allDataForNode[key] = value;
},
getAll: function (node, createIfNotFound) {
var dataStoreKey = node[ko.utils.domData.dataStoreKeyExpandoPropertyName];
if (!dataStoreKey) {
if (!createIfNotFound)
return undefined;
dataStoreKey = node[ko.utils.domData.dataStoreKeyExpandoPropertyName] = "ko" + ko.utils.domData.uniqueId++;
ko.utils.domData[dataStoreKey] = {};
}
return ko.utils.domData[dataStoreKey];
},
cleanNode: function (node) {
var dataStoreKey = node[ko.utils.domData.dataStoreKeyExpandoPropertyName];
if (dataStoreKey) {
delete ko.utils.domData[dataStoreKey];
node[ko.utils.domData.dataStoreKeyExpandoPropertyName] = null;
}
},
cleanNodeAndDescendants: function (node) {
if ((node.nodeType != 1) && (node.nodeType != 9))
return;
ko.utils.domData.cleanNode(node);
var descendants = node.getElementsByTagName("*");
for (var i = 0, j = descendants.length; i < j; i++)
ko.utils.domData.cleanNode(descendants[i]);
}
}
}
})();
ko.exportSymbol('ko.utils', ko.utils);
ko.exportSymbol('ko.utils.arrayMap', ko.utils.arrayMap);
ko.exportSymbol('ko.utils.arrayForEach', ko.utils.arrayForEach);
ko.exportSymbol('ko.utils.arrayFirst', ko.utils.arrayFirst);
ko.exportSymbol('ko.utils.arrayFilter', ko.utils.arrayFilter);
ko.exportSymbol('ko.utils.getFormFields', ko.utils.getFormFields);
ko.exportSymbol('ko.utils.postJson', ko.utils.postJson);
ko.exportSymbol('ko.utils.triggerEvent', ko.utils.triggerEvent);
ko.exportSymbol('ko.utils.unwrapObservable', ko.utils.unwrapObservable);
if (!Function.prototype['bind']) {
// Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
// In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
Function.prototype['bind'] = function (object) {
var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function () {
return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
};
};
}