forked from knockout/knockout
/
defaultBindings.js
executable file
·401 lines (362 loc) · 19 KB
/
defaultBindings.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// For certain common events (currently just 'click'), allow a simplified data-binding syntax
// e.g. click:handler instead of the usual full-length event:{click:handler}
var eventHandlersWithShortcuts = ['click'];
ko.utils.arrayForEach(eventHandlersWithShortcuts, function(eventName) {
ko.bindingHandlers[eventName] = {
'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
var newValueAccessor = function () {
var result = {};
result[eventName] = valueAccessor();
return result;
};
return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
}
}
});
ko.bindingHandlers['event'] = {
'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
var eventsToHandle = valueAccessor() || {};
for(var eventNameOutsideClosure in eventsToHandle) {
(function() {
var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
if (typeof eventName == "string") {
ko.utils.registerEventHandler(element, eventName, function (event) {
var handlerReturnValue;
var handlerFunction = valueAccessor()[eventName];
var allBindings = allBindingsAccessor();
try {
handlerReturnValue = handlerFunction.apply(viewModel, arguments);
} finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
var bubble = allBindings[eventName + 'Bubble'] !== false;
if (!bubble) {
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
}
});
}
})();
}
}
};
ko.bindingHandlers['submit'] = {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
if (typeof valueAccessor() != "function")
throw new Error("The value for a submit binding must be a function to invoke on submit");
ko.utils.registerEventHandler(element, "submit", function (event) {
var handlerReturnValue;
var value = valueAccessor();
try { handlerReturnValue = value.call(viewModel, element); }
finally {
if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
}
});
}
};
ko.bindingHandlers['visible'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var isCurrentlyVisible = !(element.style.display == "none");
if (value && !isCurrentlyVisible)
element.style.display = "";
else if ((!value) && isCurrentlyVisible)
element.style.display = "none";
}
}
ko.bindingHandlers['enable'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value && element.disabled)
element.removeAttribute("disabled");
else if ((!value) && (!element.disabled))
element.disabled = true;
}
};
ko.bindingHandlers['disable'] = {
'update': function (element, valueAccessor) {
ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
}
};
ko.bindingHandlers['value'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
var eventName = allBindingsAccessor()["valueUpdate"] || "change";
// The syntax "after<eventname>" means "run the handler asynchronously after the event"
// This is useful, for example, to catch "keydown" events after the browser has updated the control
// (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
var handleEventAsynchronously = false;
if (ko.utils.stringStartsWith(eventName, "after")) {
handleEventAsynchronously = true;
eventName = eventName.substring("after".length);
}
var runEventHandler = handleEventAsynchronously ? function(handler) { setTimeout(handler, 0) }
: function(handler) { handler() };
ko.utils.registerEventHandler(element, eventName, function () {
runEventHandler(function() {
var modelValue = valueAccessor();
var elementValue = ko.selectExtensions.readValue(element);
if (ko.isWriteableObservable(modelValue))
modelValue(elementValue);
else {
var allBindings = allBindingsAccessor();
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['value'])
allBindings['_ko_property_writers']['value'](elementValue);
}
});
});
},
'update': function (element, valueAccessor) {
var newValue = ko.utils.unwrapObservable(valueAccessor());
var elementValue = ko.selectExtensions.readValue(element);
var valueHasChanged = (newValue != elementValue);
// JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
// We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
valueHasChanged = true;
if (valueHasChanged) {
var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
applyValueAction();
// Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
// right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
// to apply the value as well.
var alsoApplyAsynchronously = element.tagName == "SELECT";
if (alsoApplyAsynchronously)
setTimeout(applyValueAction, 0);
}
// For SELECT nodes, you're not allowed to have a model value that disagrees with the UI selection, so if there is a
// difference, treat it as a change that should be written back to the model
if (element.tagName == "SELECT") {
elementValue = ko.selectExtensions.readValue(element);
if(elementValue !== newValue)
ko.utils.triggerEvent(element, "change");
}
}
};
ko.bindingHandlers['options'] = {
'update': function (element, valueAccessor, allBindingsAccessor) {
if (element.tagName != "SELECT")
throw new Error("options binding applies only to SELECT elements");
var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
return node.tagName && node.tagName == "OPTION" && node.selected;
}), function (node) {
return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
});
var previousScrollTop = element.scrollTop;
var value = ko.utils.unwrapObservable(valueAccessor());
var selectedValue = element.value;
ko.utils.emptyDomNode(element);
if (value) {
var allBindings = allBindingsAccessor();
if (typeof value.length != "number")
value = [value];
if (allBindings['optionsCaption']) {
var option = document.createElement("OPTION");
option.innerHTML = allBindings['optionsCaption'];
ko.selectExtensions.writeValue(option, undefined);
element.appendChild(option);
}
for (var i = 0, j = value.length; i < j; i++) {
var option = document.createElement("OPTION");
var optionValue = typeof allBindings['optionsValue'] == "string" ? value[i][allBindings['optionsValue']] : value[i];
// Pick some text to appear in the drop-down list for this data value
var optionsTextValue = allBindings['optionsText'];
if (typeof optionsTextValue == "function")
optionText = optionsTextValue(value[i]); // Given a function; run it against the data value
else if (typeof optionsTextValue == "string")
optionText = value[i][optionsTextValue]; // Given a string; treat it as a property name on the data value
else
optionText = optionValue; // Given no optionsText arg; use the data value itself
optionValue = ko.utils.unwrapObservable(optionValue);
optionText = ko.utils.unwrapObservable(optionText);
ko.selectExtensions.writeValue(option, optionValue);
option.innerHTML = optionText.toString();
element.appendChild(option);
}
// IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
// That's why we first added them without selection. Now it's time to set the selection.
var newOptions = element.getElementsByTagName("OPTION");
var countSelectionsRetained = 0;
for (var i = 0, j = newOptions.length; i < j; i++) {
if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
ko.utils.setOptionNodeSelectionState(newOptions[i], true);
countSelectionsRetained++;
}
}
if (previousScrollTop)
element.scrollTop = previousScrollTop;
}
}
};
ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.bindingHandlers.options.optionValueDomData__';
ko.bindingHandlers['selectedOptions'] = {
getSelectedValuesFromSelectNode: function (selectNode) {
var result = [];
var nodes = selectNode.childNodes;
for (var i = 0, j = nodes.length; i < j; i++) {
var node = nodes[i];
if ((node.tagName == "OPTION") && node.selected)
result.push(ko.selectExtensions.readValue(node));
}
return result;
},
'init': function (element, valueAccessor, allBindingsAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
var value = valueAccessor();
if (ko.isWriteableObservable(value))
value(ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this));
else {
var allBindings = allBindingsAccessor();
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['value'])
allBindings['_ko_property_writers']['value'](ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this));
}
});
},
'update': function (element, valueAccessor) {
if (element.tagName != "SELECT")
throw new Error("values binding applies only to SELECT elements");
var newValue = ko.utils.unwrapObservable(valueAccessor());
if (newValue && typeof newValue.length == "number") {
var nodes = element.childNodes;
for (var i = 0, j = nodes.length; i < j; i++) {
var node = nodes[i];
if (node.tagName == "OPTION")
ko.utils.setOptionNodeSelectionState(node, ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0);
}
}
}
};
ko.bindingHandlers['text'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if ((value === null) || (value === undefined))
value = "";
typeof element.innerText == "string" ? element.innerText = value
: element.textContent = value;
}
};
ko.bindingHandlers['html'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if ((value === null) || (value === undefined))
value = "";
element.innerHTML = value;
}
};
ko.bindingHandlers['css'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
for (var className in value) {
if (typeof className == "string") {
var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
}
}
}
};
ko.bindingHandlers['style'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
for (var styleName in value) {
if (typeof styleName == "string") {
var styleValue = ko.utils.unwrapObservable(value[styleName]);
element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
}
}
}
};
ko.bindingHandlers['uniqueName'] = {
'init': function (element, valueAccessor) {
if (valueAccessor()) {
element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
// Workaround IE 6 issue - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
if (ko.utils.isIe6)
element.mergeAttributes(document.createElement("<INPUT name='" + element.name + "'/>"), false);
}
}
};
ko.bindingHandlers['uniqueName'].currentIndex = 0;
ko.bindingHandlers['checked'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
var updateHandler = function() {
var valueToWrite;
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
} else {
return; // "checked" binding only responds to checkboxes and selected radio buttons
}
var modelValue = valueAccessor();
if ((element.type == "checkbox") && (ko.utils.unwrapObservable(modelValue) instanceof Array)) {
// For checkboxes bound to an array, we add/remove the checkbox value to that array
// This works for both observable and non-observable arrays
var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.unwrapObservable(modelValue), element.value);
if (element.checked && (existingEntryIndex < 0))
modelValue.push(element.value);
else if ((!element.checked) && (existingEntryIndex >= 0))
modelValue.splice(existingEntryIndex, 1);
} else if (ko.isWriteableObservable(modelValue)) {
if (modelValue() !== valueToWrite) { // Suppress repeated events when there's nothing new to notify (some browsers raise them)
modelValue(valueToWrite);
}
} else {
var allBindings = allBindingsAccessor();
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['checked']) {
allBindings['_ko_property_writers']['checked'](valueToWrite);
}
}
};
ko.utils.registerEventHandler(element, "change", updateHandler);
ko.utils.registerEventHandler(element, "click", updateHandler);
// IE 6 won't allow radio buttons to be selected unless they have a name
if ((element.type == "radio") && !element.name)
ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
},
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (element.type == "checkbox") {
if (value instanceof Array) {
// When bound to an array, the checkbox being checked represents its value being present in that array
element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
} else {
// When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
element.checked = value;
}
// Workaround for IE 6 bug - it fails to apply checked state to dynamically-created checkboxes if you merely say "element.checked = true"
if (value && ko.utils.isIe6)
element.mergeAttributes(document.createElement("<INPUT type='checkbox' checked='checked' />"), false);
} else if (element.type == "radio") {
element.checked = (element.value == value);
// Workaround for IE 6/7 bug - it fails to apply checked state to dynamically-created radio buttons if you merely say "element.checked = true"
if ((element.value == value) && (ko.utils.isIe6 || ko.utils.isIe7))
element.mergeAttributes(document.createElement("<INPUT type='radio' checked='checked' />"), false);
}
}
};
ko.bindingHandlers['attr'] = {
update: function(element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()) || {};
for (var attrName in value) {
if (typeof attrName == "string") {
var attrValue = ko.utils.unwrapObservable(value[attrName]);
// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp===false (because that's how to mark an element as not checked, not disabled, etc.)
if (attrValue === false)
element.removeAttribute(attrName);
else
element.setAttribute(attrName, attrValue.toString());
}
}
}
};