1 // Knockout JavaScript library v3.0.0
2 // (c) Steven Sanderson - http://knockoutjs.com/
3 // License: MIT (http://www.opensource.org/licenses/mit-license.php)
8 // (0, eval)('this') is a robust way of getting a reference to the global object
9 // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
10 var window
= this || (0, eval
)('this'),
11 document
= window
['document'],
12 navigator
= window
['navigator'],
13 jQuery
= window
["jQuery"],
14 JSON
= window
["JSON"];
16 // Support three module loading scenarios
17 if (typeof require
=== 'function' && typeof exports
=== 'object' && typeof module
=== 'object') {
18 // [1] CommonJS/Node.js
19 var target
= module
['exports'] || exports
; // module.exports is for Node.js
21 } else if (typeof define
=== 'function' && define
['amd']) {
22 // [2] AMD anonymous module
23 define(['exports'], factory
);
25 // [3] No module loader (plain <script> tag) - put directly in global namespace
26 factory(window
['ko'] = {});
28 }(function(koExports
){
29 // Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
30 // In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
31 var ko
= typeof koExports
!== 'undefined' ? koExports
: {};
32 // Google Closure Compiler helpers (used only to make the minified file smaller)
33 ko
.exportSymbol = function(koPath
, object
) {
34 var tokens
= koPath
.split(".");
36 // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
37 // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
40 for (var i
= 0; i
< tokens
.length
- 1; i
++)
41 target
= target
[tokens
[i
]];
42 target
[tokens
[tokens
.length
- 1]] = object
;
44 ko
.exportProperty = function(owner
, publicName
, object
) {
45 owner
[publicName
] = object
;
49 ko
.exportSymbol('version', ko
.version
);
50 ko
.utils
= (function () {
51 var objectForEach = function(obj
, action
) {
52 for (var prop
in obj
) {
53 if (obj
.hasOwnProperty(prop
)) {
54 action(prop
, obj
[prop
]);
59 // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
60 var knownEvents
= {}, knownEventTypesByEventName
= {};
61 var keyEventTypeName
= (navigator
&& /Firefox\/2/i.test(navigator
.userAgent
)) ? 'KeyboardEvent' : 'UIEvents';
62 knownEvents
[keyEventTypeName
] = ['keyup', 'keydown', 'keypress'];
63 knownEvents
['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
64 objectForEach(knownEvents
, function(eventType
, knownEventsForType
) {
65 if (knownEventsForType
.length
) {
66 for (var i
= 0, j
= knownEventsForType
.length
; i
< j
; i
++)
67 knownEventTypesByEventName
[knownEventsForType
[i
]] = eventType
;
70 var eventsThatMustBeRegisteredUsingAttachEvent
= { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
72 // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
73 // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
74 // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
75 // If there is a future need to detect specific versions of IE10+, we will amend this.
76 var ieVersion
= document
&& (function() {
77 var version
= 3, div
= document
.createElement('div'), iElems
= div
.getElementsByTagName('i');
79 // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
81 div
.innerHTML
= '<!--[if gt IE ' + (++version
) + ']><i></i><![endif]-->',
84 return version
> 4 ? version
: undefined;
86 var isIe6
= ieVersion
=== 6,
87 isIe7
= ieVersion
=== 7;
89 function isClickOnCheckableElement(element
, eventType
) {
90 if ((ko
.utils
.tagNameLower(element
) !== "input") || !element
.type
) return false;
91 if (eventType
.toLowerCase() != "click") return false;
92 var inputType
= element
.type
;
93 return (inputType
== "checkbox") || (inputType
== "radio");
97 fieldsIncludedWithJsonPost
: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
99 arrayForEach: function (array
, action
) {
100 for (var i
= 0, j
= array
.length
; i
< j
; i
++)
104 arrayIndexOf: function (array
, item
) {
105 if (typeof Array
.prototype.indexOf
== "function")
106 return Array
.prototype.indexOf
.call(array
, item
);
107 for (var i
= 0, j
= array
.length
; i
< j
; i
++)
108 if (array
[i
] === item
)
113 arrayFirst: function (array
, predicate
, predicateOwner
) {
114 for (var i
= 0, j
= array
.length
; i
< j
; i
++)
115 if (predicate
.call(predicateOwner
, array
[i
]))
120 arrayRemoveItem: function (array
, itemToRemove
) {
121 var index
= ko
.utils
.arrayIndexOf(array
, itemToRemove
);
123 array
.splice(index
, 1);
126 arrayGetDistinctValues: function (array
) {
129 for (var i
= 0, j
= array
.length
; i
< j
; i
++) {
130 if (ko
.utils
.arrayIndexOf(result
, array
[i
]) < 0)
131 result
.push(array
[i
]);
136 arrayMap: function (array
, mapping
) {
139 for (var i
= 0, j
= array
.length
; i
< j
; i
++)
140 result
.push(mapping(array
[i
]));
144 arrayFilter: function (array
, predicate
) {
147 for (var i
= 0, j
= array
.length
; i
< j
; i
++)
148 if (predicate(array
[i
]))
149 result
.push(array
[i
]);
153 arrayPushAll: function (array
, valuesToPush
) {
154 if (valuesToPush
instanceof Array
)
155 array
.push
.apply(array
, valuesToPush
);
157 for (var i
= 0, j
= valuesToPush
.length
; i
< j
; i
++)
158 array
.push(valuesToPush
[i
]);
162 addOrRemoveItem: function(array
, value
, included
) {
163 var existingEntryIndex
= ko
.utils
.arrayIndexOf(ko
.utils
.peekObservable(array
), value
);
164 if (existingEntryIndex
< 0) {
169 array
.splice(existingEntryIndex
, 1);
173 extend: function (target
, source
) {
175 for(var prop
in source
) {
176 if(source
.hasOwnProperty(prop
)) {
177 target
[prop
] = source
[prop
];
184 objectForEach
: objectForEach
,
186 objectMap: function(source
, mapping
) {
190 for (var prop
in source
) {
191 if (source
.hasOwnProperty(prop
)) {
192 target
[prop
] = mapping(source
[prop
], prop
, source
);
198 emptyDomNode: function (domNode
) {
199 while (domNode
.firstChild
) {
200 ko
.removeNode(domNode
.firstChild
);
204 moveCleanedNodesToContainerElement: function(nodes
) {
205 // Ensure it's a real array, as we're about to reparent the nodes and
206 // we don't want the underlying collection to change while we're doing that.
207 var nodesArray
= ko
.utils
.makeArray(nodes
);
209 var container
= document
.createElement('div');
210 for (var i
= 0, j
= nodesArray
.length
; i
< j
; i
++) {
211 container
.appendChild(ko
.cleanNode(nodesArray
[i
]));
216 cloneNodes: function (nodesArray
, shouldCleanNodes
) {
217 for (var i
= 0, j
= nodesArray
.length
, newNodesArray
= []; i
< j
; i
++) {
218 var clonedNode
= nodesArray
[i
].cloneNode(true);
219 newNodesArray
.push(shouldCleanNodes
? ko
.cleanNode(clonedNode
) : clonedNode
);
221 return newNodesArray
;
224 setDomNodeChildren: function (domNode
, childNodes
) {
225 ko
.utils
.emptyDomNode(domNode
);
227 for (var i
= 0, j
= childNodes
.length
; i
< j
; i
++)
228 domNode
.appendChild(childNodes
[i
]);
232 replaceDomNodes: function (nodeToReplaceOrNodeArray
, newNodesArray
) {
233 var nodesToReplaceArray
= nodeToReplaceOrNodeArray
.nodeType
? [nodeToReplaceOrNodeArray
] : nodeToReplaceOrNodeArray
;
234 if (nodesToReplaceArray
.length
> 0) {
235 var insertionPoint
= nodesToReplaceArray
[0];
236 var parent
= insertionPoint
.parentNode
;
237 for (var i
= 0, j
= newNodesArray
.length
; i
< j
; i
++)
238 parent
.insertBefore(newNodesArray
[i
], insertionPoint
);
239 for (var i
= 0, j
= nodesToReplaceArray
.length
; i
< j
; i
++) {
240 ko
.removeNode(nodesToReplaceArray
[i
]);
245 fixUpContinuousNodeArray: function(continuousNodeArray
, parentNode
) {
246 // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
247 // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
248 // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
249 // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
250 // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
253 // [A] Any leading nodes that have been removed should be ignored
254 // These most likely correspond to memoization nodes that were already removed during binding
255 // See https://github.com/SteveSanderson/knockout/pull/440
256 // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
257 // and include any nodes that have been inserted among the previous collection
259 if (continuousNodeArray
.length
) {
260 // The parent node can be a virtual element; so get the real parent node
261 parentNode
= (parentNode
.nodeType
=== 8 && parentNode
.parentNode
) || parentNode
;
264 while (continuousNodeArray
.length
&& continuousNodeArray
[0].parentNode
!== parentNode
)
265 continuousNodeArray
.splice(0, 1);
268 if (continuousNodeArray
.length
> 1) {
269 var current
= continuousNodeArray
[0], last
= continuousNodeArray
[continuousNodeArray
.length
- 1];
270 // Replace with the actual new continuous node set
271 continuousNodeArray
.length
= 0;
272 while (current
!== last
) {
273 continuousNodeArray
.push(current
);
274 current
= current
.nextSibling
;
275 if (!current
) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
278 continuousNodeArray
.push(last
);
281 return continuousNodeArray
;
284 setOptionNodeSelectionState: function (optionNode
, isSelected
) {
285 // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
287 optionNode
.setAttribute("selected", isSelected
);
289 optionNode
.selected
= isSelected
;
292 stringTrim: function (string
) {
293 return string
=== null || string
=== undefined ? '' :
296 string
.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
299 stringTokenize: function (string
, delimiter
) {
301 var tokens
= (string
|| "").split(delimiter
);
302 for (var i
= 0, j
= tokens
.length
; i
< j
; i
++) {
303 var trimmed
= ko
.utils
.stringTrim(tokens
[i
]);
305 result
.push(trimmed
);
310 stringStartsWith: function (string
, startsWith
) {
311 string
= string
|| "";
312 if (startsWith
.length
> string
.length
)
314 return string
.substring(0, startsWith
.length
) === startsWith
;
317 domNodeIsContainedBy: function (node
, containedByNode
) {
318 if (node
=== containedByNode
)
320 if (node
.nodeType
=== 11)
321 return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
322 if (containedByNode
.contains
)
323 return containedByNode
.contains(node
.nodeType
=== 3 ? node
.parentNode
: node
);
324 if (containedByNode
.compareDocumentPosition
)
325 return (containedByNode
.compareDocumentPosition(node
) & 16) == 16;
326 while (node
&& node
!= containedByNode
) {
327 node
= node
.parentNode
;
332 domNodeIsAttachedToDocument: function (node
) {
333 return ko
.utils
.domNodeIsContainedBy(node
, node
.ownerDocument
.documentElement
);
336 anyDomNodeIsAttachedToDocument: function(nodes
) {
337 return !!ko
.utils
.arrayFirst(nodes
, ko
.utils
.domNodeIsAttachedToDocument
);
340 tagNameLower: function(element
) {
341 // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
342 // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
343 // we don't need to do the .toLowerCase() as it will always be lower case anyway.
344 return element
&& element
.tagName
&& element
.tagName
.toLowerCase();
347 registerEventHandler: function (element
, eventType
, handler
) {
348 var mustUseAttachEvent
= ieVersion
&& eventsThatMustBeRegisteredUsingAttachEvent
[eventType
];
349 if (!mustUseAttachEvent
&& typeof jQuery
!= "undefined") {
350 if (isClickOnCheckableElement(element
, eventType
)) {
351 // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
352 // it toggles the element checked state *after* the click event handlers run, whereas native
353 // click events toggle the checked state *before* the event handler.
354 // Fix this by intecepting the handler and applying the correct checkedness before it runs.
355 var originalHandler
= handler
;
356 handler = function(event
, eventData
) {
357 var jQuerySuppliedCheckedState
= this.checked
;
359 this.checked
= eventData
.checkedStateBeforeEvent
!== true;
360 originalHandler
.call(this, event
);
361 this.checked
= jQuerySuppliedCheckedState
; // Restore the state jQuery applied
364 jQuery(element
)['bind'](eventType
, handler
);
365 } else if (!mustUseAttachEvent
&& typeof element
.addEventListener
== "function")
366 element
.addEventListener(eventType
, handler
, false);
367 else if (typeof element
.attachEvent
!= "undefined") {
368 var attachEventHandler = function (event
) { handler
.call(element
, event
); },
369 attachEventName
= "on" + eventType
;
370 element
.attachEvent(attachEventName
, attachEventHandler
);
372 // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
373 // so to avoid leaks, we have to remove them manually. See bug #856
374 ko
.utils
.domNodeDisposal
.addDisposeCallback(element
, function() {
375 element
.detachEvent(attachEventName
, attachEventHandler
);
378 throw new Error("Browser doesn't support addEventListener or attachEvent");
381 triggerEvent: function (element
, eventType
) {
382 if (!(element
&& element
.nodeType
))
383 throw new Error("element must be a DOM node when calling triggerEvent");
385 if (typeof jQuery
!= "undefined") {
387 if (isClickOnCheckableElement(element
, eventType
)) {
388 // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
389 eventData
.push({ checkedStateBeforeEvent
: element
.checked
});
391 jQuery(element
)['trigger'](eventType
, eventData
);
392 } else if (typeof document
.createEvent
== "function") {
393 if (typeof element
.dispatchEvent
== "function") {
394 var eventCategory
= knownEventTypesByEventName
[eventType
] || "HTMLEvents";
395 var event
= document
.createEvent(eventCategory
);
396 event
.initEvent(eventType
, true, true, window
, 0, 0, 0, 0, 0, false, false, false, false, 0, element
);
397 element
.dispatchEvent(event
);
400 throw new Error("The supplied element doesn't support dispatchEvent");
401 } else if (typeof element
.fireEvent
!= "undefined") {
402 // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
403 // so to make it consistent, we'll do it manually here
404 if (isClickOnCheckableElement(element
, eventType
))
405 element
.checked
= element
.checked
!== true;
406 element
.fireEvent("on" + eventType
);
409 throw new Error("Browser doesn't support triggering events");
412 unwrapObservable: function (value
) {
413 return ko
.isObservable(value
) ? value() : value
;
416 peekObservable: function (value
) {
417 return ko
.isObservable(value
) ? value
.peek() : value
;
420 toggleDomNodeCssClass: function (node
, classNames
, shouldHaveClass
) {
422 var cssClassNameRegex
= /\S+/g,
423 currentClassNames
= node
.className
.match(cssClassNameRegex
) || [];
424 ko
.utils
.arrayForEach(classNames
.match(cssClassNameRegex
), function(className
) {
425 ko
.utils
.addOrRemoveItem(currentClassNames
, className
, shouldHaveClass
);
427 node
.className
= currentClassNames
.join(" ");
431 setTextContent: function(element
, textContent
) {
432 var value
= ko
.utils
.unwrapObservable(textContent
);
433 if ((value
=== null) || (value
=== undefined))
436 // We need there to be exactly one child: a text node.
437 // If there are no children, more than one, or if it's not a text node,
438 // we'll clear everything and create a single text node.
439 var innerTextNode
= ko
.virtualElements
.firstChild(element
);
440 if (!innerTextNode
|| innerTextNode
.nodeType
!= 3 || ko
.virtualElements
.nextSibling(innerTextNode
)) {
441 ko
.virtualElements
.setDomNodeChildren(element
, [document
.createTextNode(value
)]);
443 innerTextNode
.data
= value
;
446 ko
.utils
.forceRefresh(element
);
449 setElementName: function(element
, name
) {
452 // Workaround IE 6/7 issue
453 // - https://github.com/SteveSanderson/knockout/issues/197
454 // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
455 if (ieVersion
<= 7) {
457 element
.mergeAttributes(document
.createElement("<input name='" + element
.name
+ "'/>"), false);
459 catch(e
) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
463 forceRefresh: function(node
) {
464 // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
465 if (ieVersion
>= 9) {
466 // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
467 var elem
= node
.nodeType
== 1 ? node
: node
.parentNode
;
469 elem
.style
.zoom
= elem
.style
.zoom
;
473 ensureSelectElementIsRenderedCorrectly: function(selectElement
) {
474 // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
475 // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
476 // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
478 var originalWidth
= selectElement
.style
.width
;
479 selectElement
.style
.width
= 0;
480 selectElement
.style
.width
= originalWidth
;
484 range: function (min
, max
) {
485 min
= ko
.utils
.unwrapObservable(min
);
486 max
= ko
.utils
.unwrapObservable(max
);
488 for (var i
= min
; i
<= max
; i
++)
493 makeArray: function(arrayLikeObject
) {
495 for (var i
= 0, j
= arrayLikeObject
.length
; i
< j
; i
++) {
496 result
.push(arrayLikeObject
[i
]);
503 ieVersion
: ieVersion
,
505 getFormFields: function(form
, fieldName
) {
506 var fields
= ko
.utils
.makeArray(form
.getElementsByTagName("input")).concat(ko
.utils
.makeArray(form
.getElementsByTagName("textarea")));
507 var isMatchingField
= (typeof fieldName
== 'string')
508 ? function(field
) { return field
.name
=== fieldName
}
509 : function(field
) { return fieldName
.test(field
.name
) }; // Treat fieldName as regex or object containing predicate
511 for (var i
= fields
.length
- 1; i
>= 0; i
--) {
512 if (isMatchingField(fields
[i
]))
513 matches
.push(fields
[i
]);
518 parseJson: function (jsonString
) {
519 if (typeof jsonString
== "string") {
520 jsonString
= ko
.utils
.stringTrim(jsonString
);
522 if (JSON
&& JSON
.parse
) // Use native parsing where available
523 return JSON
.parse(jsonString
);
524 return (new Function("return " + jsonString
))(); // Fallback on less safe parsing for older browsers
530 stringifyJson: function (data
, replacer
, space
) { // replacer and space are optional
531 if (!JSON
|| !JSON
.stringify
)
532 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");
533 return JSON
.stringify(ko
.utils
.unwrapObservable(data
), replacer
, space
);
536 postJson: function (urlOrForm
, data
, options
) {
537 options
= options
|| {};
538 var params
= options
['params'] || {};
539 var includeFields
= options
['includeFields'] || this.fieldsIncludedWithJsonPost
;
542 // If we were given a form, use its 'action' URL and pick out any requested field values
543 if((typeof urlOrForm
== 'object') && (ko
.utils
.tagNameLower(urlOrForm
) === "form")) {
544 var originalForm
= urlOrForm
;
545 url
= originalForm
.action
;
546 for (var i
= includeFields
.length
- 1; i
>= 0; i
--) {
547 var fields
= ko
.utils
.getFormFields(originalForm
, includeFields
[i
]);
548 for (var j
= fields
.length
- 1; j
>= 0; j
--)
549 params
[fields
[j
].name
] = fields
[j
].value
;
553 data
= ko
.utils
.unwrapObservable(data
);
554 var form
= document
.createElement("form");
555 form
.style
.display
= "none";
557 form
.method
= "post";
558 for (var key
in data
) {
559 // Since 'data' this is a model object, we include all properties including those inherited from its prototype
560 var input
= document
.createElement("input");
562 input
.value
= ko
.utils
.stringifyJson(ko
.utils
.unwrapObservable(data
[key
]));
563 form
.appendChild(input
);
565 objectForEach(params
, function(key
, value
) {
566 var input
= document
.createElement("input");
569 form
.appendChild(input
);
571 document
.body
.appendChild(form
);
572 options
['submitter'] ? options
['submitter'](form
) : form
.submit();
573 setTimeout(function () { form
.parentNode
.removeChild(form
); }, 0);
578 ko
.exportSymbol('utils', ko
.utils
);
579 ko
.exportSymbol('utils.arrayForEach', ko
.utils
.arrayForEach
);
580 ko
.exportSymbol('utils.arrayFirst', ko
.utils
.arrayFirst
);
581 ko
.exportSymbol('utils.arrayFilter', ko
.utils
.arrayFilter
);
582 ko
.exportSymbol('utils.arrayGetDistinctValues', ko
.utils
.arrayGetDistinctValues
);
583 ko
.exportSymbol('utils.arrayIndexOf', ko
.utils
.arrayIndexOf
);
584 ko
.exportSymbol('utils.arrayMap', ko
.utils
.arrayMap
);
585 ko
.exportSymbol('utils.arrayPushAll', ko
.utils
.arrayPushAll
);
586 ko
.exportSymbol('utils.arrayRemoveItem', ko
.utils
.arrayRemoveItem
);
587 ko
.exportSymbol('utils.extend', ko
.utils
.extend
);
588 ko
.exportSymbol('utils.fieldsIncludedWithJsonPost', ko
.utils
.fieldsIncludedWithJsonPost
);
589 ko
.exportSymbol('utils.getFormFields', ko
.utils
.getFormFields
);
590 ko
.exportSymbol('utils.peekObservable', ko
.utils
.peekObservable
);
591 ko
.exportSymbol('utils.postJson', ko
.utils
.postJson
);
592 ko
.exportSymbol('utils.parseJson', ko
.utils
.parseJson
);
593 ko
.exportSymbol('utils.registerEventHandler', ko
.utils
.registerEventHandler
);
594 ko
.exportSymbol('utils.stringifyJson', ko
.utils
.stringifyJson
);
595 ko
.exportSymbol('utils.range', ko
.utils
.range
);
596 ko
.exportSymbol('utils.toggleDomNodeCssClass', ko
.utils
.toggleDomNodeCssClass
);
597 ko
.exportSymbol('utils.triggerEvent', ko
.utils
.triggerEvent
);
598 ko
.exportSymbol('utils.unwrapObservable', ko
.utils
.unwrapObservable
);
599 ko
.exportSymbol('utils.objectForEach', ko
.utils
.objectForEach
);
600 ko
.exportSymbol('utils.addOrRemoveItem', ko
.utils
.addOrRemoveItem
);
601 ko
.exportSymbol('unwrap', ko
.utils
.unwrapObservable
); // Convenient shorthand, because this is used so commonly
603 if (!Function
.prototype['bind']) {
604 // 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)
605 // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
606 Function
.prototype['bind'] = function (object
) {
607 var originalFunction
= this, args
= Array
.prototype.slice
.call(arguments
), object
= args
.shift();
609 return originalFunction
.apply(object
, args
.concat(Array
.prototype.slice
.call(arguments
)));
614 ko
.utils
.domData
= new (function () {
616 var dataStoreKeyExpandoPropertyName
= "__ko__" + (new Date
).getTime();
619 function getAll(node
, createIfNotFound
) {
620 var dataStoreKey
= node
[dataStoreKeyExpandoPropertyName
];
621 var hasExistingDataStore
= dataStoreKey
&& (dataStoreKey
!== "null") && dataStore
[dataStoreKey
];
622 if (!hasExistingDataStore
) {
623 if (!createIfNotFound
)
625 dataStoreKey
= node
[dataStoreKeyExpandoPropertyName
] = "ko" + uniqueId
++;
626 dataStore
[dataStoreKey
] = {};
628 return dataStore
[dataStoreKey
];
632 get: function (node
, key
) {
633 var allDataForNode
= getAll(node
, false);
634 return allDataForNode
=== undefined ? undefined : allDataForNode
[key
];
636 set: function (node
, key
, value
) {
637 if (value
=== undefined) {
638 // Make sure we don't actually create a new domData key if we are actually deleting a value
639 if (getAll(node
, false) === undefined)
642 var allDataForNode
= getAll(node
, true);
643 allDataForNode
[key
] = value
;
645 clear: function (node
) {
646 var dataStoreKey
= node
[dataStoreKeyExpandoPropertyName
];
648 delete dataStore
[dataStoreKey
];
649 node
[dataStoreKeyExpandoPropertyName
] = null;
650 return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
655 nextKey: function () {
656 return (uniqueId
++) + dataStoreKeyExpandoPropertyName
;
661 ko
.exportSymbol('utils.domData', ko
.utils
.domData
);
662 ko
.exportSymbol('utils.domData.clear', ko
.utils
.domData
.clear
); // Exporting only so specs can clear up after themselves fully
664 ko
.utils
.domNodeDisposal
= new (function () {
665 var domDataKey
= ko
.utils
.domData
.nextKey();
666 var cleanableNodeTypes
= { 1: true, 8: true, 9: true }; // Element, Comment, Document
667 var cleanableNodeTypesWithDescendants
= { 1: true, 9: true }; // Element, Document
669 function getDisposeCallbacksCollection(node
, createIfNotFound
) {
670 var allDisposeCallbacks
= ko
.utils
.domData
.get(node
, domDataKey
);
671 if ((allDisposeCallbacks
=== undefined) && createIfNotFound
) {
672 allDisposeCallbacks
= [];
673 ko
.utils
.domData
.set(node
, domDataKey
, allDisposeCallbacks
);
675 return allDisposeCallbacks
;
677 function destroyCallbacksCollection(node
) {
678 ko
.utils
.domData
.set(node
, domDataKey
, undefined);
681 function cleanSingleNode(node
) {
682 // Run all the dispose callbacks
683 var callbacks
= getDisposeCallbacksCollection(node
, false);
685 callbacks
= callbacks
.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
686 for (var i
= 0; i
< callbacks
.length
; i
++)
690 // Also erase the DOM data
691 ko
.utils
.domData
.clear(node
);
693 // Special support for jQuery here because it's so commonly used.
694 // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
695 // so notify it to tear down any resources associated with the node & descendants here.
696 if ((typeof jQuery
== "function") && (typeof jQuery
['cleanData'] == "function"))
697 jQuery
['cleanData']([node
]);
699 // Also clear any immediate-child comment nodes, as these wouldn't have been found by
700 // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
701 if (cleanableNodeTypesWithDescendants
[node
.nodeType
])
702 cleanImmediateCommentTypeChildren(node
);
705 function cleanImmediateCommentTypeChildren(nodeWithChildren
) {
706 var child
, nextChild
= nodeWithChildren
.firstChild
;
707 while (child
= nextChild
) {
708 nextChild
= child
.nextSibling
;
709 if (child
.nodeType
=== 8)
710 cleanSingleNode(child
);
715 addDisposeCallback : function(node
, callback
) {
716 if (typeof callback
!= "function")
717 throw new Error("Callback must be a function");
718 getDisposeCallbacksCollection(node
, true).push(callback
);
721 removeDisposeCallback : function(node
, callback
) {
722 var callbacksCollection
= getDisposeCallbacksCollection(node
, false);
723 if (callbacksCollection
) {
724 ko
.utils
.arrayRemoveItem(callbacksCollection
, callback
);
725 if (callbacksCollection
.length
== 0)
726 destroyCallbacksCollection(node
);
730 cleanNode : function(node
) {
731 // First clean this node, where applicable
732 if (cleanableNodeTypes
[node
.nodeType
]) {
733 cleanSingleNode(node
);
735 // ... then its descendants, where applicable
736 if (cleanableNodeTypesWithDescendants
[node
.nodeType
]) {
737 // Clone the descendants list in case it changes during iteration
738 var descendants
= [];
739 ko
.utils
.arrayPushAll(descendants
, node
.getElementsByTagName("*"));
740 for (var i
= 0, j
= descendants
.length
; i
< j
; i
++)
741 cleanSingleNode(descendants
[i
]);
747 removeNode : function(node
) {
750 node
.parentNode
.removeChild(node
);
754 ko
.cleanNode
= ko
.utils
.domNodeDisposal
.cleanNode
; // Shorthand name for convenience
755 ko
.removeNode
= ko
.utils
.domNodeDisposal
.removeNode
; // Shorthand name for convenience
756 ko
.exportSymbol('cleanNode', ko
.cleanNode
);
757 ko
.exportSymbol('removeNode', ko
.removeNode
);
758 ko
.exportSymbol('utils.domNodeDisposal', ko
.utils
.domNodeDisposal
);
759 ko
.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko
.utils
.domNodeDisposal
.addDisposeCallback
);
760 ko
.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko
.utils
.domNodeDisposal
.removeDisposeCallback
);
762 var leadingCommentRegex
= /^(\s*)<!--(.*?)-->/;
764 function simpleHtmlParse(html
) {
765 // Based on jQuery's "clean" function, but only accounting for table-related elements.
766 // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
768 // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
769 // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
770 // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
771 // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
773 // Trim whitespace, otherwise indexOf won't work as expected
774 var tags
= ko
.utils
.stringTrim(html
).toLowerCase(), div
= document
.createElement("div");
776 // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
777 var wrap
= tags
.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
778 !tags
.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
779 (!tags
.indexOf("<td") || !tags
.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
780 /* anything else */ [0, "", ""];
782 // Go to html and back, then peel off extra wrappers
783 // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
784 var markup
= "ignored<div>" + wrap
[1] + html
+ wrap
[2] + "</div>";
785 if (typeof window
['innerShiv'] == "function") {
786 div
.appendChild(window
['innerShiv'](markup
));
788 div
.innerHTML
= markup
;
791 // Move to the right depth
795 return ko
.utils
.makeArray(div
.lastChild
.childNodes
);
798 function jQueryHtmlParse(html
) {
799 // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
800 if (jQuery
['parseHTML']) {
801 return jQuery
['parseHTML'](html
) || []; // Ensure we always return an array and never null
803 // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
804 var elems
= jQuery
['clean']([html
]);
806 // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
807 // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
808 // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
809 if (elems
&& elems
[0]) {
810 // Find the top-most parent element that's a direct child of a document fragment
812 while (elem
.parentNode
&& elem
.parentNode
.nodeType
!== 11 /* i.e., DocumentFragment */)
813 elem
= elem
.parentNode
;
814 // ... then detach it
816 elem
.parentNode
.removeChild(elem
);
823 ko
.utils
.parseHtmlFragment = function(html
) {
824 return typeof jQuery
!= 'undefined' ? jQueryHtmlParse(html
) // As below, benefit from jQuery's optimisations where possible
825 : simpleHtmlParse(html
); // ... otherwise, this simple logic will do in most common cases.
828 ko
.utils
.setHtml = function(node
, html
) {
829 ko
.utils
.emptyDomNode(node
);
831 // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
832 html
= ko
.utils
.unwrapObservable(html
);
834 if ((html
!== null) && (html
!== undefined)) {
835 if (typeof html
!= 'string')
836 html
= html
.toString();
838 // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
839 // for example <tr> elements which are not normally allowed to exist on their own.
840 // If you've referenced jQuery we'll use that rather than duplicating its code.
841 if (typeof jQuery
!= 'undefined') {
842 jQuery(node
)['html'](html
);
844 // ... otherwise, use KO's own parsing logic.
845 var parsedNodes
= ko
.utils
.parseHtmlFragment(html
);
846 for (var i
= 0; i
< parsedNodes
.length
; i
++)
847 node
.appendChild(parsedNodes
[i
]);
853 ko
.exportSymbol('utils.parseHtmlFragment', ko
.utils
.parseHtmlFragment
);
854 ko
.exportSymbol('utils.setHtml', ko
.utils
.setHtml
);
856 ko
.memoization
= (function () {
859 function randomMax8HexChars() {
860 return (((1 + Math
.random()) * 0x100000000) | 0).toString(16).substring(1);
862 function generateRandomId() {
863 return randomMax8HexChars() + randomMax8HexChars();
865 function findMemoNodes(rootNode
, appendToArray
) {
868 if (rootNode
.nodeType
== 8) {
869 var memoId
= ko
.memoization
.parseMemoText(rootNode
.nodeValue
);
871 appendToArray
.push({ domNode
: rootNode
, memoId
: memoId
});
872 } else if (rootNode
.nodeType
== 1) {
873 for (var i
= 0, childNodes
= rootNode
.childNodes
, j
= childNodes
.length
; i
< j
; i
++)
874 findMemoNodes(childNodes
[i
], appendToArray
);
879 memoize: function (callback
) {
880 if (typeof callback
!= "function")
881 throw new Error("You can only pass a function to ko.memoization.memoize()");
882 var memoId
= generateRandomId();
883 memos
[memoId
] = callback
;
884 return "<!--[ko_memo:" + memoId
+ "]-->";
887 unmemoize: function (memoId
, callbackParams
) {
888 var callback
= memos
[memoId
];
889 if (callback
=== undefined)
890 throw new Error("Couldn't find any memo with ID " + memoId
+ ". Perhaps it's already been unmemoized.");
892 callback
.apply(null, callbackParams
|| []);
895 finally { delete memos
[memoId
]; }
898 unmemoizeDomNodeAndDescendants: function (domNode
, extraCallbackParamsArray
) {
900 findMemoNodes(domNode
, memos
);
901 for (var i
= 0, j
= memos
.length
; i
< j
; i
++) {
902 var node
= memos
[i
].domNode
;
903 var combinedParams
= [node
];
904 if (extraCallbackParamsArray
)
905 ko
.utils
.arrayPushAll(combinedParams
, extraCallbackParamsArray
);
906 ko
.memoization
.unmemoize(memos
[i
].memoId
, combinedParams
);
907 node
.nodeValue
= ""; // Neuter this node so we don't try to unmemoize it again
909 node
.parentNode
.removeChild(node
); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
913 parseMemoText: function (memoText
) {
914 var match
= memoText
.match(/^\[ko_memo\:(.*?)\]$/);
915 return match
? match
[1] : null;
920 ko
.exportSymbol('memoization', ko
.memoization
);
921 ko
.exportSymbol('memoization.memoize', ko
.memoization
.memoize
);
922 ko
.exportSymbol('memoization.unmemoize', ko
.memoization
.unmemoize
);
923 ko
.exportSymbol('memoization.parseMemoText', ko
.memoization
.parseMemoText
);
924 ko
.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko
.memoization
.unmemoizeDomNodeAndDescendants
);
926 'throttle': function(target
, timeout
) {
927 // Throttling means two things:
929 // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
930 // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
931 target
['throttleEvaluation'] = timeout
;
933 // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
934 // so the target cannot change value synchronously or faster than a certain rate
935 var writeTimeoutInstance
= null;
936 return ko
.dependentObservable({
938 'write': function(value
) {
939 clearTimeout(writeTimeoutInstance
);
940 writeTimeoutInstance
= setTimeout(function() {
947 'notify': function(target
, notifyWhen
) {
948 target
["equalityComparer"] = notifyWhen
== "always" ?
949 null : // null equalityComparer means to always notify
950 valuesArePrimitiveAndEqual
;
954 var primitiveTypes
= { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
955 function valuesArePrimitiveAndEqual(a
, b
) {
956 var oldValueIsPrimitive
= (a
=== null) || (typeof(a
) in primitiveTypes
);
957 return oldValueIsPrimitive
? (a
=== b
) : false;
960 function applyExtenders(requestedExtenders
) {
962 if (requestedExtenders
) {
963 ko
.utils
.objectForEach(requestedExtenders
, function(key
, value
) {
964 var extenderHandler
= ko
.extenders
[key
];
965 if (typeof extenderHandler
== 'function') {
966 target
= extenderHandler(target
, value
) || target
;
973 ko
.exportSymbol('extenders', ko
.extenders
);
975 ko
.subscription = function (target
, callback
, disposeCallback
) {
976 this.target
= target
;
977 this.callback
= callback
;
978 this.disposeCallback
= disposeCallback
;
979 ko
.exportProperty(this, 'dispose', this.dispose
);
981 ko
.subscription
.prototype.dispose = function () {
982 this.isDisposed
= true;
983 this.disposeCallback();
986 ko
.subscribable = function () {
987 this._subscriptions
= {};
989 ko
.utils
.extend(this, ko
.subscribable
['fn']);
990 ko
.exportProperty(this, 'subscribe', this.subscribe
);
991 ko
.exportProperty(this, 'extend', this.extend
);
992 ko
.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount
);
995 var defaultEvent
= "change";
997 ko
.subscribable
['fn'] = {
998 subscribe: function (callback
, callbackTarget
, event
) {
999 event
= event
|| defaultEvent
;
1000 var boundCallback
= callbackTarget
? callback
.bind(callbackTarget
) : callback
;
1002 var subscription
= new ko
.subscription(this, boundCallback
, function () {
1003 ko
.utils
.arrayRemoveItem(this._subscriptions
[event
], subscription
);
1006 if (!this._subscriptions
[event
])
1007 this._subscriptions
[event
] = [];
1008 this._subscriptions
[event
].push(subscription
);
1009 return subscription
;
1012 "notifySubscribers": function (valueToNotify
, event
) {
1013 event
= event
|| defaultEvent
;
1014 if (this.hasSubscriptionsForEvent(event
)) {
1016 ko
.dependencyDetection
.begin();
1017 for (var a
= this._subscriptions
[event
].slice(0), i
= 0, subscription
; subscription
= a
[i
]; ++i
) {
1018 // In case a subscription was disposed during the arrayForEach cycle, check
1019 // for isDisposed on each subscription before invoking its callback
1020 if (subscription
&& (subscription
.isDisposed
!== true))
1021 subscription
.callback(valueToNotify
);
1024 ko
.dependencyDetection
.end();
1029 hasSubscriptionsForEvent: function(event
) {
1030 return this._subscriptions
[event
] && this._subscriptions
[event
].length
;
1033 getSubscriptionsCount: function () {
1035 ko
.utils
.objectForEach(this._subscriptions
, function(eventName
, subscriptions
) {
1036 total
+= subscriptions
.length
;
1041 extend
: applyExtenders
1045 ko
.isSubscribable = function (instance
) {
1046 return instance
!= null && typeof instance
.subscribe
== "function" && typeof instance
["notifySubscribers"] == "function";
1049 ko
.exportSymbol('subscribable', ko
.subscribable
);
1050 ko
.exportSymbol('isSubscribable', ko
.isSubscribable
);
1052 ko
.dependencyDetection
= (function () {
1056 begin: function (callback
) {
1057 _frames
.push(callback
&& { callback
: callback
, distinctDependencies
:[] });
1064 registerDependency: function (subscribable
) {
1065 if (!ko
.isSubscribable(subscribable
))
1066 throw new Error("Only subscribable things can act as dependencies");
1067 if (_frames
.length
> 0) {
1068 var topFrame
= _frames
[_frames
.length
- 1];
1069 if (!topFrame
|| ko
.utils
.arrayIndexOf(topFrame
.distinctDependencies
, subscribable
) >= 0)
1071 topFrame
.distinctDependencies
.push(subscribable
);
1072 topFrame
.callback(subscribable
);
1076 ignore: function(callback
, callbackTarget
, callbackArgs
) {
1079 return callback
.apply(callbackTarget
, callbackArgs
|| []);
1086 ko
.observable = function (initialValue
) {
1087 var _latestValue
= initialValue
;
1089 function observable() {
1090 if (arguments
.length
> 0) {
1093 // Ignore writes if the value hasn't changed
1094 if (!observable
['equalityComparer'] || !observable
['equalityComparer'](_latestValue
, arguments
[0])) {
1095 observable
.valueWillMutate();
1096 _latestValue
= arguments
[0];
1097 if (DEBUG
) observable
._latestValue
= _latestValue
;
1098 observable
.valueHasMutated();
1100 return this; // Permits chained assignments
1104 ko
.dependencyDetection
.registerDependency(observable
); // The caller only needs to be notified of changes if they did a "read" operation
1105 return _latestValue
;
1108 if (DEBUG
) observable
._latestValue
= _latestValue
;
1109 ko
.subscribable
.call(observable
);
1110 observable
.peek = function() { return _latestValue
};
1111 observable
.valueHasMutated = function () { observable
["notifySubscribers"](_latestValue
); }
1112 observable
.valueWillMutate = function () { observable
["notifySubscribers"](_latestValue
, "beforeChange"); }
1113 ko
.utils
.extend(observable
, ko
.observable
['fn']);
1115 ko
.exportProperty(observable
, 'peek', observable
.peek
);
1116 ko
.exportProperty(observable
, "valueHasMutated", observable
.valueHasMutated
);
1117 ko
.exportProperty(observable
, "valueWillMutate", observable
.valueWillMutate
);
1122 ko
.observable
['fn'] = {
1123 "equalityComparer": valuesArePrimitiveAndEqual
1126 var protoProperty
= ko
.observable
.protoProperty
= "__ko_proto__";
1127 ko
.observable
['fn'][protoProperty
] = ko
.observable
;
1129 ko
.hasPrototype = function(instance
, prototype) {
1130 if ((instance
=== null) || (instance
=== undefined) || (instance
[protoProperty
] === undefined)) return false;
1131 if (instance
[protoProperty
] === prototype) return true;
1132 return ko
.hasPrototype(instance
[protoProperty
], prototype); // Walk the prototype chain
1135 ko
.isObservable = function (instance
) {
1136 return ko
.hasPrototype(instance
, ko
.observable
);
1138 ko
.isWriteableObservable = function (instance
) {
1140 if ((typeof instance
== "function") && instance
[protoProperty
] === ko
.observable
)
1142 // Writeable dependent observable
1143 if ((typeof instance
== "function") && (instance
[protoProperty
] === ko
.dependentObservable
) && (instance
.hasWriteFunction
))
1150 ko
.exportSymbol('observable', ko
.observable
);
1151 ko
.exportSymbol('isObservable', ko
.isObservable
);
1152 ko
.exportSymbol('isWriteableObservable', ko
.isWriteableObservable
);
1153 ko
.observableArray = function (initialValues
) {
1154 initialValues
= initialValues
|| [];
1156 if (typeof initialValues
!= 'object' || !('length' in initialValues
))
1157 throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
1159 var result
= ko
.observable(initialValues
);
1160 ko
.utils
.extend(result
, ko
.observableArray
['fn']);
1161 return result
.extend({'trackArrayChanges':true});
1164 ko
.observableArray
['fn'] = {
1165 'remove': function (valueOrPredicate
) {
1166 var underlyingArray
= this.peek();
1167 var removedValues
= [];
1168 var predicate
= typeof valueOrPredicate
== "function" && !ko
.isObservable(valueOrPredicate
) ? valueOrPredicate : function (value
) { return value
=== valueOrPredicate
; };
1169 for (var i
= 0; i
< underlyingArray
.length
; i
++) {
1170 var value
= underlyingArray
[i
];
1171 if (predicate(value
)) {
1172 if (removedValues
.length
=== 0) {
1173 this.valueWillMutate();
1175 removedValues
.push(value
);
1176 underlyingArray
.splice(i
, 1);
1180 if (removedValues
.length
) {
1181 this.valueHasMutated();
1183 return removedValues
;
1186 'removeAll': function (arrayOfValues
) {
1187 // If you passed zero args, we remove everything
1188 if (arrayOfValues
=== undefined) {
1189 var underlyingArray
= this.peek();
1190 var allValues
= underlyingArray
.slice(0);
1191 this.valueWillMutate();
1192 underlyingArray
.splice(0, underlyingArray
.length
);
1193 this.valueHasMutated();
1196 // If you passed an arg, we interpret it as an array of entries to remove
1199 return this['remove'](function (value
) {
1200 return ko
.utils
.arrayIndexOf(arrayOfValues
, value
) >= 0;
1204 'destroy': function (valueOrPredicate
) {
1205 var underlyingArray
= this.peek();
1206 var predicate
= typeof valueOrPredicate
== "function" && !ko
.isObservable(valueOrPredicate
) ? valueOrPredicate : function (value
) { return value
=== valueOrPredicate
; };
1207 this.valueWillMutate();
1208 for (var i
= underlyingArray
.length
- 1; i
>= 0; i
--) {
1209 var value
= underlyingArray
[i
];
1210 if (predicate(value
))
1211 underlyingArray
[i
]["_destroy"] = true;
1213 this.valueHasMutated();
1216 'destroyAll': function (arrayOfValues
) {
1217 // If you passed zero args, we destroy everything
1218 if (arrayOfValues
=== undefined)
1219 return this['destroy'](function() { return true });
1221 // If you passed an arg, we interpret it as an array of entries to destroy
1224 return this['destroy'](function (value
) {
1225 return ko
.utils
.arrayIndexOf(arrayOfValues
, value
) >= 0;
1229 'indexOf': function (item
) {
1230 var underlyingArray
= this();
1231 return ko
.utils
.arrayIndexOf(underlyingArray
, item
);
1234 'replace': function(oldItem
, newItem
) {
1235 var index
= this['indexOf'](oldItem
);
1237 this.valueWillMutate();
1238 this.peek()[index
] = newItem
;
1239 this.valueHasMutated();
1244 // Populate ko.observableArray.fn with read/write functions from native arrays
1245 // Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
1246 // because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
1247 ko
.utils
.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName
) {
1248 ko
.observableArray
['fn'][methodName
] = function () {
1249 // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
1250 // (for consistency with mutating regular observables)
1251 var underlyingArray
= this.peek();
1252 this.valueWillMutate();
1253 this.cacheDiffForKnownOperation(underlyingArray
, methodName
, arguments
);
1254 var methodCallResult
= underlyingArray
[methodName
].apply(underlyingArray
, arguments
);
1255 this.valueHasMutated();
1256 return methodCallResult
;
1260 // Populate ko.observableArray.fn with read-only functions from native arrays
1261 ko
.utils
.arrayForEach(["slice"], function (methodName
) {
1262 ko
.observableArray
['fn'][methodName
] = function () {
1263 var underlyingArray
= this();
1264 return underlyingArray
[methodName
].apply(underlyingArray
, arguments
);
1268 ko
.exportSymbol('observableArray', ko
.observableArray
);
1269 var arrayChangeEventName
= 'arrayChange';
1270 ko
.extenders
['trackArrayChanges'] = function(target
) {
1271 // Only modify the target observable once
1272 if (target
.cacheDiffForKnownOperation
) {
1275 var trackingChanges
= false,
1277 pendingNotifications
= 0,
1278 underlyingSubscribeFunction
= target
.subscribe
;
1280 // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
1281 target
.subscribe
= target
['subscribe'] = function(callback
, callbackTarget
, event
) {
1282 if (event
=== arrayChangeEventName
) {
1285 return underlyingSubscribeFunction
.apply(this, arguments
);
1288 function trackChanges() {
1289 // Calling 'trackChanges' multiple times is the same as calling it once
1290 if (trackingChanges
) {
1294 trackingChanges
= true;
1296 // Intercept "notifySubscribers" to track how many times it was called.
1297 var underlyingNotifySubscribersFunction
= target
['notifySubscribers'];
1298 target
['notifySubscribers'] = function(valueToNotify
, event
) {
1299 if (!event
|| event
=== defaultEvent
) {
1300 ++pendingNotifications
;
1302 return underlyingNotifySubscribersFunction
.apply(this, arguments
);
1305 // Each time the array changes value, capture a clone so that on the next
1306 // change it's possible to produce a diff
1307 var previousContents
= [].concat(target
.peek() || []);
1309 target
.subscribe(function(currentContents
) {
1310 // Make a copy of the current contents and ensure it's an array
1311 currentContents
= [].concat(currentContents
|| []);
1313 // Compute the diff and issue notifications, but only if someone is listening
1314 if (target
.hasSubscriptionsForEvent(arrayChangeEventName
)) {
1315 var changes
= getChanges(previousContents
, currentContents
);
1316 if (changes
.length
) {
1317 target
['notifySubscribers'](changes
, arrayChangeEventName
);
1321 // Eliminate references to the old, removed items, so they can be GCed
1322 previousContents
= currentContents
;
1324 pendingNotifications
= 0;
1328 function getChanges(previousContents
, currentContents
) {
1329 // We try to re-use cached diffs.
1330 // The only scenario where pendingNotifications > 1 is when using the KO 'deferred updates' plugin,
1331 // which without this check would not be compatible with arrayChange notifications. Without that
1332 // plugin, notifications are always issued immediately so we wouldn't be queueing up more than one.
1333 if (!cachedDiff
|| pendingNotifications
> 1) {
1334 cachedDiff
= ko
.utils
.compareArrays(previousContents
, currentContents
, { 'sparse': true });
1340 target
.cacheDiffForKnownOperation = function(rawArray
, operationName
, args
) {
1341 // Only run if we're currently tracking changes for this observable array
1342 // and there aren't any pending deferred notifications.
1343 if (!trackingChanges
|| pendingNotifications
) {
1347 arrayLength
= rawArray
.length
,
1348 argsLength
= args
.length
,
1351 function pushDiff(status
, value
, index
) {
1352 diff
.push({ 'status': status
, 'value': value
, 'index': index
});
1354 switch (operationName
) {
1356 offset
= arrayLength
;
1358 for (var index
= 0; index
< argsLength
; index
++) {
1359 pushDiff('added', args
[index
], offset
+ index
);
1364 offset
= arrayLength
- 1;
1367 pushDiff('deleted', rawArray
[offset
], offset
);
1372 // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
1373 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
1374 var startIndex
= Math
.min(Math
.max(0, args
[0] < 0 ? arrayLength
+ args
[0] : args
[0]), arrayLength
),
1375 endDeleteIndex
= argsLength
=== 1 ? arrayLength
: Math
.min(startIndex
+ (args
[1] || 0), arrayLength
),
1376 endAddIndex
= startIndex
+ argsLength
- 2,
1377 endIndex
= Math
.max(endDeleteIndex
, endAddIndex
);
1378 for (var index
= startIndex
, argsIndex
= 2; index
< endIndex
; ++index
, ++argsIndex
) {
1379 if (index
< endDeleteIndex
)
1380 pushDiff('deleted', rawArray
[index
], index
);
1381 if (index
< endAddIndex
)
1382 pushDiff('added', args
[argsIndex
], index
);
1392 ko
.dependentObservable = function (evaluatorFunctionOrOptions
, evaluatorFunctionTarget
, options
) {
1394 _hasBeenEvaluated
= false,
1395 _isBeingEvaluated
= false,
1396 _suppressDisposalUntilDisposeWhenReturnsFalse
= false,
1397 readFunction
= evaluatorFunctionOrOptions
;
1399 if (readFunction
&& typeof readFunction
== "object") {
1400 // Single-parameter syntax - everything is on this "options" param
1401 options
= readFunction
;
1402 readFunction
= options
["read"];
1404 // Multi-parameter syntax - construct the options according to the params passed
1405 options
= options
|| {};
1407 readFunction
= options
["read"];
1409 if (typeof readFunction
!= "function")
1410 throw new Error("Pass a function that returns the value of the ko.computed");
1412 function addSubscriptionToDependency(subscribable
) {
1413 _subscriptionsToDependencies
.push(subscribable
.subscribe(evaluatePossiblyAsync
));
1416 function disposeAllSubscriptionsToDependencies() {
1417 ko
.utils
.arrayForEach(_subscriptionsToDependencies
, function (subscription
) {
1418 subscription
.dispose();
1420 _subscriptionsToDependencies
= [];
1423 function evaluatePossiblyAsync() {
1424 var throttleEvaluationTimeout
= dependentObservable
['throttleEvaluation'];
1425 if (throttleEvaluationTimeout
&& throttleEvaluationTimeout
>= 0) {
1426 clearTimeout(evaluationTimeoutInstance
);
1427 evaluationTimeoutInstance
= setTimeout(evaluateImmediate
, throttleEvaluationTimeout
);
1429 evaluateImmediate();
1432 function evaluateImmediate() {
1433 if (_isBeingEvaluated
) {
1434 // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
1435 // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
1436 // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
1437 // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
1441 if (disposeWhen
&& disposeWhen()) {
1442 // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
1443 if (!_suppressDisposalUntilDisposeWhenReturnsFalse
) {
1445 _hasBeenEvaluated
= true;
1449 // It just did return false, so we can stop suppressing now
1450 _suppressDisposalUntilDisposeWhenReturnsFalse
= false;
1453 _isBeingEvaluated
= true;
1455 // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
1456 // Then, during evaluation, we cross off any that are in fact still being used.
1457 var disposalCandidates
= ko
.utils
.arrayMap(_subscriptionsToDependencies
, function(item
) {return item
.target
;});
1459 ko
.dependencyDetection
.begin(function(subscribable
) {
1461 if ((inOld
= ko
.utils
.arrayIndexOf(disposalCandidates
, subscribable
)) >= 0)
1462 disposalCandidates
[inOld
] = undefined; // Don't want to dispose this subscription, as it's still being used
1464 addSubscriptionToDependency(subscribable
); // Brand new subscription - add it
1467 var newValue
= evaluatorFunctionTarget
? readFunction
.call(evaluatorFunctionTarget
) : readFunction();
1469 // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
1470 for (var i
= disposalCandidates
.length
- 1; i
>= 0; i
--) {
1471 if (disposalCandidates
[i
])
1472 _subscriptionsToDependencies
.splice(i
, 1)[0].dispose();
1474 _hasBeenEvaluated
= true;
1476 if (!dependentObservable
['equalityComparer'] || !dependentObservable
['equalityComparer'](_latestValue
, newValue
)) {
1477 dependentObservable
["notifySubscribers"](_latestValue
, "beforeChange");
1479 _latestValue
= newValue
;
1480 if (DEBUG
) dependentObservable
._latestValue
= _latestValue
;
1481 dependentObservable
["notifySubscribers"](_latestValue
);
1484 ko
.dependencyDetection
.end();
1485 _isBeingEvaluated
= false;
1488 if (!_subscriptionsToDependencies
.length
)
1492 function dependentObservable() {
1493 if (arguments
.length
> 0) {
1494 if (typeof writeFunction
=== "function") {
1496 writeFunction
.apply(evaluatorFunctionTarget
, arguments
);
1498 throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
1500 return this; // Permits chained assignments
1502 // Reading the value
1503 if (!_hasBeenEvaluated
)
1504 evaluateImmediate();
1505 ko
.dependencyDetection
.registerDependency(dependentObservable
);
1506 return _latestValue
;
1511 if (!_hasBeenEvaluated
)
1512 evaluateImmediate();
1513 return _latestValue
;
1516 function isActive() {
1517 return !_hasBeenEvaluated
|| _subscriptionsToDependencies
.length
> 0;
1520 // By here, "options" is always non-null
1521 var writeFunction
= options
["write"],
1522 disposeWhenNodeIsRemoved
= options
["disposeWhenNodeIsRemoved"] || options
.disposeWhenNodeIsRemoved
|| null,
1523 disposeWhenOption
= options
["disposeWhen"] || options
.disposeWhen
,
1524 disposeWhen
= disposeWhenOption
,
1525 dispose
= disposeAllSubscriptionsToDependencies
,
1526 _subscriptionsToDependencies
= [],
1527 evaluationTimeoutInstance
= null;
1529 if (!evaluatorFunctionTarget
)
1530 evaluatorFunctionTarget
= options
["owner"];
1532 dependentObservable
.peek
= peek
;
1533 dependentObservable
.getDependenciesCount = function () { return _subscriptionsToDependencies
.length
; };
1534 dependentObservable
.hasWriteFunction
= typeof options
["write"] === "function";
1535 dependentObservable
.dispose = function () { dispose(); };
1536 dependentObservable
.isActive
= isActive
;
1538 ko
.subscribable
.call(dependentObservable
);
1539 ko
.utils
.extend(dependentObservable
, ko
.dependentObservable
['fn']);
1541 ko
.exportProperty(dependentObservable
, 'peek', dependentObservable
.peek
);
1542 ko
.exportProperty(dependentObservable
, 'dispose', dependentObservable
.dispose
);
1543 ko
.exportProperty(dependentObservable
, 'isActive', dependentObservable
.isActive
);
1544 ko
.exportProperty(dependentObservable
, 'getDependenciesCount', dependentObservable
.getDependenciesCount
);
1546 // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
1547 if (disposeWhenNodeIsRemoved
) {
1548 // Since this computed is associated with a DOM node, and we don't want to dispose the computed
1549 // until the DOM node is *removed* from the document (as opposed to never having been in the document),
1550 // we'll prevent disposal until "disposeWhen" first returns false.
1551 _suppressDisposalUntilDisposeWhenReturnsFalse
= true;
1553 // Only watch for the node's disposal if the value really is a node. It might not be,
1554 // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
1555 // after first false result" behaviour even if there's no specific node to watch. This
1556 // technique is intended for KO's internal use only and shouldn't be documented or used
1557 // by application code, as it's likely to change in a future version of KO.
1558 if (disposeWhenNodeIsRemoved
.nodeType
) {
1559 disposeWhen = function () {
1560 return !ko
.utils
.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved
) || (disposeWhenOption
&& disposeWhenOption());
1565 // Evaluate, unless deferEvaluation is true
1566 if (options
['deferEvaluation'] !== true)
1567 evaluateImmediate();
1569 // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
1570 // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
1571 if (disposeWhenNodeIsRemoved
&& isActive()) {
1572 dispose = function() {
1573 ko
.utils
.domNodeDisposal
.removeDisposeCallback(disposeWhenNodeIsRemoved
, dispose
);
1574 disposeAllSubscriptionsToDependencies();
1576 ko
.utils
.domNodeDisposal
.addDisposeCallback(disposeWhenNodeIsRemoved
, dispose
);
1579 return dependentObservable
;
1582 ko
.isComputed = function(instance
) {
1583 return ko
.hasPrototype(instance
, ko
.dependentObservable
);
1586 var protoProp
= ko
.observable
.protoProperty
; // == "__ko_proto__"
1587 ko
.dependentObservable
[protoProp
] = ko
.observable
;
1589 ko
.dependentObservable
['fn'] = {
1590 "equalityComparer": valuesArePrimitiveAndEqual
1592 ko
.dependentObservable
['fn'][protoProp
] = ko
.dependentObservable
;
1594 ko
.exportSymbol('dependentObservable', ko
.dependentObservable
);
1595 ko
.exportSymbol('computed', ko
.dependentObservable
); // Make "ko.computed" an alias for "ko.dependentObservable"
1596 ko
.exportSymbol('isComputed', ko
.isComputed
);
1599 var maxNestedObservableDepth
= 10; // Escape the (unlikely) pathological case where an observable's current value is itself (or similar reference cycle)
1601 ko
.toJS = function(rootObject
) {
1602 if (arguments
.length
== 0)
1603 throw new Error("When calling ko.toJS, pass the object you want to convert.");
1605 // We just unwrap everything at every level in the object graph
1606 return mapJsObjectGraph(rootObject
, function(valueToMap
) {
1607 // Loop because an observable's value might in turn be another observable wrapper
1608 for (var i
= 0; ko
.isObservable(valueToMap
) && (i
< maxNestedObservableDepth
); i
++)
1609 valueToMap
= valueToMap();
1614 ko
.toJSON = function(rootObject
, replacer
, space
) { // replacer and space are optional
1615 var plainJavaScriptObject
= ko
.toJS(rootObject
);
1616 return ko
.utils
.stringifyJson(plainJavaScriptObject
, replacer
, space
);
1619 function mapJsObjectGraph(rootObject
, mapInputCallback
, visitedObjects
) {
1620 visitedObjects
= visitedObjects
|| new objectLookup();
1622 rootObject
= mapInputCallback(rootObject
);
1623 var canHaveProperties
= (typeof rootObject
== "object") && (rootObject
!== null) && (rootObject
!== undefined) && (!(rootObject
instanceof Date
)) && (!(rootObject
instanceof String
)) && (!(rootObject
instanceof Number
)) && (!(rootObject
instanceof Boolean
));
1624 if (!canHaveProperties
)
1627 var outputProperties
= rootObject
instanceof Array
? [] : {};
1628 visitedObjects
.save(rootObject
, outputProperties
);
1630 visitPropertiesOrArrayEntries(rootObject
, function(indexer
) {
1631 var propertyValue
= mapInputCallback(rootObject
[indexer
]);
1633 switch (typeof propertyValue
) {
1638 outputProperties
[indexer
] = propertyValue
;
1642 var previouslyMappedValue
= visitedObjects
.get(propertyValue
);
1643 outputProperties
[indexer
] = (previouslyMappedValue
!== undefined)
1644 ? previouslyMappedValue
1645 : mapJsObjectGraph(propertyValue
, mapInputCallback
, visitedObjects
);
1650 return outputProperties
;
1653 function visitPropertiesOrArrayEntries(rootObject
, visitorCallback
) {
1654 if (rootObject
instanceof Array
) {
1655 for (var i
= 0; i
< rootObject
.length
; i
++)
1658 // For arrays, also respect toJSON property for custom mappings (fixes #278)
1659 if (typeof rootObject
['toJSON'] == 'function')
1660 visitorCallback('toJSON');
1662 for (var propertyName
in rootObject
) {
1663 visitorCallback(propertyName
);
1668 function objectLookup() {
1673 objectLookup
.prototype = {
1674 constructor: objectLookup
,
1675 save: function(key
, value
) {
1676 var existingIndex
= ko
.utils
.arrayIndexOf(this.keys
, key
);
1677 if (existingIndex
>= 0)
1678 this.values
[existingIndex
] = value
;
1680 this.keys
.push(key
);
1681 this.values
.push(value
);
1684 get: function(key
) {
1685 var existingIndex
= ko
.utils
.arrayIndexOf(this.keys
, key
);
1686 return (existingIndex
>= 0) ? this.values
[existingIndex
] : undefined;
1691 ko
.exportSymbol('toJS', ko
.toJS
);
1692 ko
.exportSymbol('toJSON', ko
.toJSON
);
1694 var hasDomDataExpandoProperty
= '__ko__hasDomDataOptionValue__';
1696 // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
1697 // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
1698 // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
1699 ko
.selectExtensions
= {
1700 readValue : function(element
) {
1701 switch (ko
.utils
.tagNameLower(element
)) {
1703 if (element
[hasDomDataExpandoProperty
] === true)
1704 return ko
.utils
.domData
.get(element
, ko
.bindingHandlers
.options
.optionValueDomDataKey
);
1705 return ko
.utils
.ieVersion
<= 7
1706 ? (element
.getAttributeNode('value') && element
.getAttributeNode('value').specified
? element
.value
: element
.text
)
1709 return element
.selectedIndex
>= 0 ? ko
.selectExtensions
.readValue(element
.options
[element
.selectedIndex
]) : undefined;
1711 return element
.value
;
1715 writeValue: function(element
, value
) {
1716 switch (ko
.utils
.tagNameLower(element
)) {
1718 switch(typeof value
) {
1720 ko
.utils
.domData
.set(element
, ko
.bindingHandlers
.options
.optionValueDomDataKey
, undefined);
1721 if (hasDomDataExpandoProperty
in element
) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
1722 delete element
[hasDomDataExpandoProperty
];
1724 element
.value
= value
;
1727 // Store arbitrary object using DomData
1728 ko
.utils
.domData
.set(element
, ko
.bindingHandlers
.options
.optionValueDomDataKey
, value
);
1729 element
[hasDomDataExpandoProperty
] = true;
1731 // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
1732 element
.value
= typeof value
=== "number" ? value
: "";
1739 if (value
=== null || value
=== undefined)
1740 element
.selectedIndex
= -1;
1741 for (var i
= element
.options
.length
- 1; i
>= 0; i
--) {
1742 if (ko
.selectExtensions
.readValue(element
.options
[i
]) == value
) {
1743 element
.selectedIndex
= i
;
1747 // for drop-down select, ensure first is selected
1748 if (!(element
.size
> 1) && element
.selectedIndex
=== -1) {
1749 element
.selectedIndex
= 0;
1753 if ((value
=== null) || (value
=== undefined))
1755 element
.value
= value
;
1762 ko
.exportSymbol('selectExtensions', ko
.selectExtensions
);
1763 ko
.exportSymbol('selectExtensions.readValue', ko
.selectExtensions
.readValue
);
1764 ko
.exportSymbol('selectExtensions.writeValue', ko
.selectExtensions
.writeValue
);
1765 ko
.expressionRewriting
= (function () {
1766 var javaScriptReservedWords
= ["true", "false", "null", "undefined"];
1768 // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
1769 // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
1770 // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
1771 var javaScriptAssignmentTarget
= /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
1773 function getWriteableValue(expression
) {
1774 if (ko
.utils
.arrayIndexOf(javaScriptReservedWords
, expression
) >= 0)
1776 var match
= expression
.match(javaScriptAssignmentTarget
);
1777 return match
=== null ? false : match
[1] ? ('Object(' + match
[1] + ')' + match
[2]) : expression
;
1780 // The following regular expressions will be used to split an object-literal string into tokens
1782 // These two match strings, either with double quotes or single quotes
1783 var stringDouble
= '"(?:[^"\\\\]|\\\\.)*"',
1784 stringSingle
= "'(?:[^'\\\\]|\\\\.)*'",
1785 // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
1786 // as a regular expression (this is handled by the parsing loop below).
1787 stringRegexp
= '/(?:[^/\\\\]|\\\\.)*/\w*',
1788 // These characters have special meaning to the parser and must not appear in the middle of a
1789 // token, except as part of a string.
1790 specials
= ',"\'{}()/:[\\]',
1791 // Match text (at least two characters) that does not contain any of the above special characters,
1792 // although some of the special characters are allowed to start it (all but the colon and comma).
1793 // The text can contain spaces, but leading or trailing spaces are skipped.
1794 everyThingElse
= '[^\\s:,/][^' + specials
+ ']*[^\\s' + specials
+ ']',
1795 // Match any non-space character not matched already. This will match colons and commas, since they're
1796 // not matched by "everyThingElse", but will also match any other single character that wasn't already
1797 // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
1798 oneNotSpace
= '[^\\s]',
1800 // Create the actual regular expression by or-ing the above strings. The order is important.
1801 bindingToken
= RegExp(stringDouble
+ '|' + stringSingle
+ '|' + stringRegexp
+ '|' + everyThingElse
+ '|' + oneNotSpace
, 'g'),
1803 // Match end of previous token to determine whether a slash is a division or regex.
1804 divisionLookBehind
= /[\])"'A-Za-z0-9_$]+$/,
1805 keywordRegexLookBehind
= {'in':1,'return':1,'typeof':1};
1807 function parseObjectLiteral(objectLiteralString
) {
1808 // Trim leading and trailing spaces from the string
1809 var str
= ko
.utils
.stringTrim(objectLiteralString
);
1811 // Trim braces '{' surrounding the whole object literal
1812 if (str
.charCodeAt(0) === 123) str
= str
.slice(1, -1);
1814 // Split into tokens
1815 var result
= [], toks
= str
.match(bindingToken
), key
, values
, depth
= 0;
1818 // Append a comma so that we don't need a separate code block to deal with the last item
1821 for (var i
= 0, tok
; tok
= toks
[i
]; ++i
) {
1822 var c
= tok
.charCodeAt(0);
1823 // A comma signals the end of a key/value pair if depth is zero
1824 if (c
=== 44) { // ","
1827 result
.push(values
? {key
: key
, value
: values
.join('')} : {'unknown': key
});
1828 key
= values
= depth
= 0;
1831 // Simply skip the colon that separates the name and value
1832 } else if (c
=== 58) { // ":"
1835 // A set of slashes is initially matched as a regular expression, but could be division
1836 } else if (c
=== 47 && i
&& tok
.length
> 1) { // "/"
1837 // Look at the end of the previous token to determine if the slash is actually division
1838 var match
= toks
[i
-1].match(divisionLookBehind
);
1839 if (match
&& !keywordRegexLookBehind
[match
[0]]) {
1840 // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
1841 str
= str
.substr(str
.indexOf(tok
) + 1);
1842 toks
= str
.match(bindingToken
);
1845 // Continue with just the slash
1848 // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
1849 } else if (c
=== 40 || c
=== 123 || c
=== 91) { // '(', '{', '['
1851 } else if (c
=== 41 || c
=== 125 || c
=== 93) { // ')', '}', ']'
1853 // The key must be a single token; if it's a string, trim the quotes
1854 } else if (!key
&& !values
) {
1855 key
= (c
=== 34 || c
=== 39) /* '"', "'" */ ? tok
.slice(1, -1) : tok
;
1867 // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
1868 var twoWayBindings
= {};
1870 function preProcessBindings(bindingsStringOrKeyValueArray
, bindingOptions
) {
1871 bindingOptions
= bindingOptions
|| {};
1873 function processKeyValue(key
, val
) {
1875 function callPreprocessHook(obj
) {
1876 return (obj
&& obj
['preprocess']) ? (val
= obj
['preprocess'](val
, key
, processKeyValue
)) : true;
1878 if (!callPreprocessHook(ko
['getBindingHandler'](key
)))
1881 if (twoWayBindings
[key
] && (writableVal
= getWriteableValue(val
))) {
1882 // For two-way bindings, provide a write method in case the value
1883 // isn't a writable observable.
1884 propertyAccessorResultStrings
.push("'" + key
+ "':function(_z){" + writableVal
+ "=_z}");
1887 // Values are wrapped in a function so that each value can be accessed independently
1888 if (makeValueAccessors
) {
1889 val
= 'function(){return ' + val
+ ' }';
1891 resultStrings
.push("'" + key
+ "':" + val
);
1894 var resultStrings
= [],
1895 propertyAccessorResultStrings
= [],
1896 makeValueAccessors
= bindingOptions
['valueAccessors'],
1897 keyValueArray
= typeof bindingsStringOrKeyValueArray
=== "string" ?
1898 parseObjectLiteral(bindingsStringOrKeyValueArray
) : bindingsStringOrKeyValueArray
;
1900 ko
.utils
.arrayForEach(keyValueArray
, function(keyValue
) {
1901 processKeyValue(keyValue
.key
|| keyValue
['unknown'], keyValue
.value
);
1904 if (propertyAccessorResultStrings
.length
)
1905 processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings
.join(",") + "}");
1907 return resultStrings
.join(",");
1911 bindingRewriteValidators
: [],
1913 twoWayBindings
: twoWayBindings
,
1915 parseObjectLiteral
: parseObjectLiteral
,
1917 preProcessBindings
: preProcessBindings
,
1919 keyValueArrayContainsKey: function(keyValueArray
, key
) {
1920 for (var i
= 0; i
< keyValueArray
.length
; i
++)
1921 if (keyValueArray
[i
]['key'] == key
)
1926 // Internal, private KO utility for updating model properties from within bindings
1927 // property: If the property being updated is (or might be) an observable, pass it here
1928 // If it turns out to be a writable observable, it will be written to directly
1929 // allBindings: An object with a get method to retrieve bindings in the current execution context.
1930 // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
1931 // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
1932 // value: The value to be written
1933 // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
1934 // it is !== existing value on that writable observable
1935 writeValueToProperty: function(property
, allBindings
, key
, value
, checkIfDifferent
) {
1936 if (!property
|| !ko
.isObservable(property
)) {
1937 var propWriters
= allBindings
.get('_ko_property_writers');
1938 if (propWriters
&& propWriters
[key
])
1939 propWriters
[key
](value
);
1940 } else if (ko
.isWriteableObservable(property
) && (!checkIfDifferent
|| property
.peek() !== value
)) {
1947 ko
.exportSymbol('expressionRewriting', ko
.expressionRewriting
);
1948 ko
.exportSymbol('expressionRewriting.bindingRewriteValidators', ko
.expressionRewriting
.bindingRewriteValidators
);
1949 ko
.exportSymbol('expressionRewriting.parseObjectLiteral', ko
.expressionRewriting
.parseObjectLiteral
);
1950 ko
.exportSymbol('expressionRewriting.preProcessBindings', ko
.expressionRewriting
.preProcessBindings
);
1952 // Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
1953 // all bindings could use an official 'property writer' API without needing to declare that they might). However,
1954 // since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
1955 // as an internal implementation detail in the short term.
1956 // For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
1957 // undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
1958 // public API, and we reserve the right to remove it at any time if we create a real public property writers API.
1959 ko
.exportSymbol('expressionRewriting._twoWayBindings', ko
.expressionRewriting
.twoWayBindings
);
1961 // For backward compatibility, define the following aliases. (Previously, these function names were misleading because
1962 // they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
1963 ko
.exportSymbol('jsonExpressionRewriting', ko
.expressionRewriting
);
1964 ko
.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko
.expressionRewriting
.preProcessBindings
);
1966 // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
1967 // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
1968 // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
1969 // of that virtual hierarchy
1971 // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
1972 // without having to scatter special cases all over the binding and templating code.
1974 // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
1975 // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
1976 // So, use node.text where available, and node.nodeValue elsewhere
1977 var commentNodesHaveTextProperty
= document
&& document
.createComment("test").text
=== "<!--test-->";
1979 var startCommentRegex
= commentNodesHaveTextProperty
? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
1980 var endCommentRegex
= commentNodesHaveTextProperty
? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
1981 var htmlTagsWithOptionallyClosingChildren
= { 'ul': true, 'ol': true };
1983 function isStartComment(node
) {
1984 return (node
.nodeType
== 8) && startCommentRegex
.test(commentNodesHaveTextProperty
? node
.text
: node
.nodeValue
);
1987 function isEndComment(node
) {
1988 return (node
.nodeType
== 8) && endCommentRegex
.test(commentNodesHaveTextProperty
? node
.text
: node
.nodeValue
);
1991 function getVirtualChildren(startComment
, allowUnbalanced
) {
1992 var currentNode
= startComment
;
1995 while (currentNode
= currentNode
.nextSibling
) {
1996 if (isEndComment(currentNode
)) {
2002 children
.push(currentNode
);
2004 if (isStartComment(currentNode
))
2007 if (!allowUnbalanced
)
2008 throw new Error("Cannot find closing comment tag to match: " + startComment
.nodeValue
);
2012 function getMatchingEndComment(startComment
, allowUnbalanced
) {
2013 var allVirtualChildren
= getVirtualChildren(startComment
, allowUnbalanced
);
2014 if (allVirtualChildren
) {
2015 if (allVirtualChildren
.length
> 0)
2016 return allVirtualChildren
[allVirtualChildren
.length
- 1].nextSibling
;
2017 return startComment
.nextSibling
;
2019 return null; // Must have no matching end comment, and allowUnbalanced is true
2022 function getUnbalancedChildTags(node
) {
2023 // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
2024 // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
2025 var childNode
= node
.firstChild
, captureRemaining
= null;
2028 if (captureRemaining
) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
2029 captureRemaining
.push(childNode
);
2030 else if (isStartComment(childNode
)) {
2031 var matchingEndComment
= getMatchingEndComment(childNode
, /* allowUnbalanced: */ true);
2032 if (matchingEndComment
) // It's a balanced tag, so skip immediately to the end of this virtual set
2033 childNode
= matchingEndComment
;
2035 captureRemaining
= [childNode
]; // It's unbalanced, so start capturing from this point
2036 } else if (isEndComment(childNode
)) {
2037 captureRemaining
= [childNode
]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
2039 } while (childNode
= childNode
.nextSibling
);
2041 return captureRemaining
;
2044 ko
.virtualElements
= {
2045 allowedBindings
: {},
2047 childNodes: function(node
) {
2048 return isStartComment(node
) ? getVirtualChildren(node
) : node
.childNodes
;
2051 emptyNode: function(node
) {
2052 if (!isStartComment(node
))
2053 ko
.utils
.emptyDomNode(node
);
2055 var virtualChildren
= ko
.virtualElements
.childNodes(node
);
2056 for (var i
= 0, j
= virtualChildren
.length
; i
< j
; i
++)
2057 ko
.removeNode(virtualChildren
[i
]);
2061 setDomNodeChildren: function(node
, childNodes
) {
2062 if (!isStartComment(node
))
2063 ko
.utils
.setDomNodeChildren(node
, childNodes
);
2065 ko
.virtualElements
.emptyNode(node
);
2066 var endCommentNode
= node
.nextSibling
; // Must be the next sibling, as we just emptied the children
2067 for (var i
= 0, j
= childNodes
.length
; i
< j
; i
++)
2068 endCommentNode
.parentNode
.insertBefore(childNodes
[i
], endCommentNode
);
2072 prepend: function(containerNode
, nodeToPrepend
) {
2073 if (!isStartComment(containerNode
)) {
2074 if (containerNode
.firstChild
)
2075 containerNode
.insertBefore(nodeToPrepend
, containerNode
.firstChild
);
2077 containerNode
.appendChild(nodeToPrepend
);
2079 // Start comments must always have a parent and at least one following sibling (the end comment)
2080 containerNode
.parentNode
.insertBefore(nodeToPrepend
, containerNode
.nextSibling
);
2084 insertAfter: function(containerNode
, nodeToInsert
, insertAfterNode
) {
2085 if (!insertAfterNode
) {
2086 ko
.virtualElements
.prepend(containerNode
, nodeToInsert
);
2087 } else if (!isStartComment(containerNode
)) {
2088 // Insert after insertion point
2089 if (insertAfterNode
.nextSibling
)
2090 containerNode
.insertBefore(nodeToInsert
, insertAfterNode
.nextSibling
);
2092 containerNode
.appendChild(nodeToInsert
);
2094 // Children of start comments must always have a parent and at least one following sibling (the end comment)
2095 containerNode
.parentNode
.insertBefore(nodeToInsert
, insertAfterNode
.nextSibling
);
2099 firstChild: function(node
) {
2100 if (!isStartComment(node
))
2101 return node
.firstChild
;
2102 if (!node
.nextSibling
|| isEndComment(node
.nextSibling
))
2104 return node
.nextSibling
;
2107 nextSibling: function(node
) {
2108 if (isStartComment(node
))
2109 node
= getMatchingEndComment(node
);
2110 if (node
.nextSibling
&& isEndComment(node
.nextSibling
))
2112 return node
.nextSibling
;
2115 hasBindingValue
: isStartComment
,
2117 virtualNodeBindingValue: function(node
) {
2118 var regexMatch
= (commentNodesHaveTextProperty
? node
.text
: node
.nodeValue
).match(startCommentRegex
);
2119 return regexMatch
? regexMatch
[1] : null;
2122 normaliseVirtualElementDomStructure: function(elementVerified
) {
2123 // Workaround for https://github.com/SteveSanderson/knockout/issues/155
2124 // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
2125 // that are direct descendants of <ul> into the preceding <li>)
2126 if (!htmlTagsWithOptionallyClosingChildren
[ko
.utils
.tagNameLower(elementVerified
)])
2129 // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
2130 // must be intended to appear *after* that child, so move them there.
2131 var childNode
= elementVerified
.firstChild
;
2134 if (childNode
.nodeType
=== 1) {
2135 var unbalancedTags
= getUnbalancedChildTags(childNode
);
2136 if (unbalancedTags
) {
2137 // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
2138 var nodeToInsertBefore
= childNode
.nextSibling
;
2139 for (var i
= 0; i
< unbalancedTags
.length
; i
++) {
2140 if (nodeToInsertBefore
)
2141 elementVerified
.insertBefore(unbalancedTags
[i
], nodeToInsertBefore
);
2143 elementVerified
.appendChild(unbalancedTags
[i
]);
2147 } while (childNode
= childNode
.nextSibling
);
2152 ko
.exportSymbol('virtualElements', ko
.virtualElements
);
2153 ko
.exportSymbol('virtualElements.allowedBindings', ko
.virtualElements
.allowedBindings
);
2154 ko
.exportSymbol('virtualElements.emptyNode', ko
.virtualElements
.emptyNode
);
2155 //ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
2156 ko
.exportSymbol('virtualElements.insertAfter', ko
.virtualElements
.insertAfter
);
2157 //ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
2158 ko
.exportSymbol('virtualElements.prepend', ko
.virtualElements
.prepend
);
2159 ko
.exportSymbol('virtualElements.setDomNodeChildren', ko
.virtualElements
.setDomNodeChildren
);
2161 var defaultBindingAttributeName
= "data-bind";
2163 ko
.bindingProvider = function() {
2164 this.bindingCache
= {};
2167 ko
.utils
.extend(ko
.bindingProvider
.prototype, {
2168 'nodeHasBindings': function(node
) {
2169 switch (node
.nodeType
) {
2170 case 1: return node
.getAttribute(defaultBindingAttributeName
) != null; // Element
2171 case 8: return ko
.virtualElements
.hasBindingValue(node
); // Comment node
2172 default: return false;
2176 'getBindings': function(node
, bindingContext
) {
2177 var bindingsString
= this['getBindingsString'](node
, bindingContext
);
2178 return bindingsString
? this['parseBindingsString'](bindingsString
, bindingContext
, node
) : null;
2181 'getBindingAccessors': function(node
, bindingContext
) {
2182 var bindingsString
= this['getBindingsString'](node
, bindingContext
);
2183 return bindingsString
? this['parseBindingsString'](bindingsString
, bindingContext
, node
, {'valueAccessors':true}) : null;
2186 // The following function is only used internally by this default provider.
2187 // It's not part of the interface definition for a general binding provider.
2188 'getBindingsString': function(node
, bindingContext
) {
2189 switch (node
.nodeType
) {
2190 case 1: return node
.getAttribute(defaultBindingAttributeName
); // Element
2191 case 8: return ko
.virtualElements
.virtualNodeBindingValue(node
); // Comment node
2192 default: return null;
2196 // The following function is only used internally by this default provider.
2197 // It's not part of the interface definition for a general binding provider.
2198 'parseBindingsString': function(bindingsString
, bindingContext
, node
, options
) {
2200 var bindingFunction
= createBindingsStringEvaluatorViaCache(bindingsString
, this.bindingCache
, options
);
2201 return bindingFunction(bindingContext
, node
);
2203 ex
.message
= "Unable to parse bindings.\nBindings value: " + bindingsString
+ "\nMessage: " + ex
.message
;
2209 ko
.bindingProvider
['instance'] = new ko
.bindingProvider();
2211 function createBindingsStringEvaluatorViaCache(bindingsString
, cache
, options
) {
2212 var cacheKey
= bindingsString
+ (options
&& options
['valueAccessors'] || '');
2213 return cache
[cacheKey
]
2214 || (cache
[cacheKey
] = createBindingsStringEvaluator(bindingsString
, options
));
2217 function createBindingsStringEvaluator(bindingsString
, options
) {
2218 // Build the source for a function that evaluates "expression"
2219 // For each scope variable, add an extra level of "with" nesting
2220 // Example result: with(sc1) { with(sc0) { return (expression) } }
2221 var rewrittenBindings
= ko
.expressionRewriting
.preProcessBindings(bindingsString
, options
),
2222 functionBody
= "with($context){with($data||{}){return{" + rewrittenBindings
+ "}}}";
2223 return new Function("$context", "$element", functionBody
);
2227 ko
.exportSymbol('bindingProvider', ko
.bindingProvider
);
2229 ko
.bindingHandlers
= {};
2231 // The following element types will not be recursed into during binding. In the future, we
2232 // may consider adding <template> to this list, because such elements' contents are always
2233 // intended to be bound in a different context from where they appear in the document.
2234 var bindingDoesNotRecurseIntoElementTypes
= {
2235 // Don't want bindings that operate on text nodes to mutate <script> contents,
2236 // because it's unexpected and a potential XSS issue
2240 // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
2241 ko
['getBindingHandler'] = function(bindingKey
) {
2242 return ko
.bindingHandlers
[bindingKey
];
2245 // The ko.bindingContext constructor is only called directly to create the root context. For child
2246 // contexts, use bindingContext.createChildContext or bindingContext.extend.
2247 ko
.bindingContext = function(dataItemOrAccessor
, parentContext
, dataItemAlias
, extendCallback
) {
2249 // The binding context object includes static properties for the current, parent, and root view models.
2250 // If a view model is actually stored in an observable, the corresponding binding context object, and
2251 // any child contexts, must be updated when the view model is changed.
2252 function updateContext() {
2253 // Most of the time, the context will directly get a view model object, but if a function is given,
2254 // we call the function to retrieve the view model. If the function accesses any obsevables (or is
2255 // itself an observable), the dependency is tracked, and those observables can later cause the binding
2256 // context to be updated.
2257 var dataItem
= isFunc
? dataItemOrAccessor() : dataItemOrAccessor
;
2259 if (parentContext
) {
2260 // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
2261 // parent context is updated, this context will also be updated.
2262 if (parentContext
._subscribable
)
2263 parentContext
._subscribable();
2265 // Copy $root and any custom properties from the parent context
2266 ko
.utils
.extend(self
, parentContext
);
2268 // Because the above copy overwrites our own properties, we need to reset them.
2269 // During the first execution, "subscribable" isn't set, so don't bother doing the update then.
2271 self
._subscribable
= subscribable
;
2274 self
['$parents'] = [];
2275 self
['$root'] = dataItem
;
2277 // Export 'ko' in the binding context so it will be available in bindings and templates
2278 // even if 'ko' isn't exported as a global, such as when using an AMD loader.
2279 // See https://github.com/SteveSanderson/knockout/issues/490
2282 self
['$rawData'] = dataItemOrAccessor
;
2283 self
['$data'] = dataItem
;
2285 self
[dataItemAlias
] = dataItem
;
2287 // The extendCallback function is provided when creating a child context or extending a context.
2288 // It handles the specific actions needed to finish setting up the binding context. Actions in this
2289 // function could also add dependencies to this binding context.
2291 extendCallback(self
, parentContext
, dataItem
);
2293 return self
['$data'];
2295 function disposeWhen() {
2296 return nodes
&& !ko
.utils
.anyDomNodeIsAttachedToDocument(nodes
);
2300 isFunc
= typeof(dataItemOrAccessor
) == "function",
2302 subscribable
= ko
.dependentObservable(updateContext
, null, { disposeWhen
: disposeWhen
, disposeWhenNodeIsRemoved
: true });
2304 // At this point, the binding context has been initialized, and the "subscribable" computed observable is
2305 // subscribed to any observables that were accessed in the process. If there is nothing to track, the
2306 // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
2307 // the context object.
2308 if (subscribable
.isActive()) {
2309 self
._subscribable
= subscribable
;
2311 // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
2312 subscribable
['equalityComparer'] = null;
2314 // We need to be able to dispose of this computed observable when it's no longer needed. This would be
2315 // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
2316 // we cannot assume that those nodes have any relation to each other. So instead we track any node that
2317 // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
2319 // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
2321 subscribable
._addNode = function(node
) {
2323 ko
.utils
.domNodeDisposal
.addDisposeCallback(node
, function(node
) {
2324 ko
.utils
.arrayRemoveItem(nodes
, node
);
2325 if (!nodes
.length
) {
2326 subscribable
.dispose();
2327 self
._subscribable
= subscribable
= undefined;
2334 // Extend the binding context hierarchy with a new view model object. If the parent context is watching
2335 // any obsevables, the new child context will automatically get a dependency on the parent context.
2336 // But this does not mean that the $data value of the child context will also get updated. If the child
2337 // view model also depends on the parent view model, you must provide a function that returns the correct
2338 // view model on each update.
2339 ko
.bindingContext
.prototype['createChildContext'] = function (dataItemOrAccessor
, dataItemAlias
, extendCallback
) {
2340 return new ko
.bindingContext(dataItemOrAccessor
, this, dataItemAlias
, function(self
, parentContext
) {
2341 // Extend the context hierarchy by setting the appropriate pointers
2342 self
['$parentContext'] = parentContext
;
2343 self
['$parent'] = parentContext
['$data'];
2344 self
['$parents'] = (parentContext
['$parents'] || []).slice(0);
2345 self
['$parents'].unshift(self
['$parent']);
2347 extendCallback(self
);
2351 // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
2352 // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
2353 // when an observable view model is updated.
2354 ko
.bindingContext
.prototype['extend'] = function(properties
) {
2355 return new ko
.bindingContext(this['$rawData'], this, null, function(self
) {
2356 ko
.utils
.extend(self
, typeof(properties
) == "function" ? properties() : properties
);
2360 // Returns the valueAccesor function for a binding value
2361 function makeValueAccessor(value
) {
2367 // Returns the value of a valueAccessor function
2368 function evaluateValueAccessor(valueAccessor
) {
2369 return valueAccessor();
2372 // Given a function that returns bindings, create and return a new object that contains
2373 // binding value-accessors functions. Each accessor function calls the original function
2374 // so that it always gets the latest value and all dependencies are captured. This is used
2375 // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
2376 function makeAccessorsFromFunction(callback
) {
2377 return ko
.utils
.objectMap(ko
.dependencyDetection
.ignore(callback
), function(value
, key
) {
2379 return callback()[key
];
2384 // Given a bindings function or object, create and return a new object that contains
2385 // binding value-accessors functions. This is used by ko.applyBindingsToNode.
2386 function makeBindingAccessors(bindings
, context
, node
) {
2387 if (typeof bindings
=== 'function') {
2388 return makeAccessorsFromFunction(bindings
.bind(null, context
, node
));
2390 return ko
.utils
.objectMap(bindings
, makeValueAccessor
);
2394 // This function is used if the binding provider doesn't include a getBindingAccessors function.
2395 // It must be called with 'this' set to the provider instance.
2396 function getBindingsAndMakeAccessors(node
, context
) {
2397 return makeAccessorsFromFunction(this['getBindings'].bind(this, node
, context
));
2400 function validateThatBindingIsAllowedForVirtualElements(bindingName
) {
2401 var validator
= ko
.virtualElements
.allowedBindings
[bindingName
];
2403 throw new Error("The binding '" + bindingName
+ "' cannot be used with virtual elements")
2406 function applyBindingsToDescendantsInternal (bindingContext
, elementOrVirtualElement
, bindingContextsMayDifferFromDomParentElement
) {
2408 nextInQueue
= ko
.virtualElements
.firstChild(elementOrVirtualElement
),
2409 provider
= ko
.bindingProvider
['instance'],
2410 preprocessNode
= provider
['preprocessNode'];
2412 // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
2413 // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
2414 // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
2415 // trigger insertion of <template> contents at that point in the document.
2416 if (preprocessNode
) {
2417 while (currentChild
= nextInQueue
) {
2418 nextInQueue
= ko
.virtualElements
.nextSibling(currentChild
);
2419 preprocessNode
.call(provider
, currentChild
);
2421 // Reset nextInQueue for the next loop
2422 nextInQueue
= ko
.virtualElements
.firstChild(elementOrVirtualElement
);
2425 while (currentChild
= nextInQueue
) {
2426 // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
2427 nextInQueue
= ko
.virtualElements
.nextSibling(currentChild
);
2428 applyBindingsToNodeAndDescendantsInternal(bindingContext
, currentChild
, bindingContextsMayDifferFromDomParentElement
);
2432 function applyBindingsToNodeAndDescendantsInternal (bindingContext
, nodeVerified
, bindingContextMayDifferFromDomParentElement
) {
2433 var shouldBindDescendants
= true;
2435 // Perf optimisation: Apply bindings only if...
2436 // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
2437 // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
2438 // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
2439 var isElement
= (nodeVerified
.nodeType
=== 1);
2440 if (isElement
) // Workaround IE <= 8 HTML parsing weirdness
2441 ko
.virtualElements
.normaliseVirtualElementDomStructure(nodeVerified
);
2443 var shouldApplyBindings
= (isElement
&& bindingContextMayDifferFromDomParentElement
) // Case (1)
2444 || ko
.bindingProvider
['instance']['nodeHasBindings'](nodeVerified
); // Case (2)
2445 if (shouldApplyBindings
)
2446 shouldBindDescendants
= applyBindingsToNodeInternal(nodeVerified
, null, bindingContext
, bindingContextMayDifferFromDomParentElement
)['shouldBindDescendants'];
2448 if (shouldBindDescendants
&& !bindingDoesNotRecurseIntoElementTypes
[ko
.utils
.tagNameLower(nodeVerified
)]) {
2449 // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
2450 // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
2451 // hence bindingContextsMayDifferFromDomParentElement is false
2452 // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
2453 // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
2454 // hence bindingContextsMayDifferFromDomParentElement is true
2455 applyBindingsToDescendantsInternal(bindingContext
, nodeVerified
, /* bindingContextsMayDifferFromDomParentElement: */ !isElement
);
2459 var boundElementDomDataKey
= ko
.utils
.domData
.nextKey();
2462 function topologicalSortBindings(bindings
) {
2464 var result
= [], // The list of key/handler pairs that we will return
2465 bindingsConsidered
= {}, // A temporary record of which bindings are already in 'result'
2466 cyclicDependencyStack
= []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
2467 ko
.utils
.objectForEach(bindings
, function pushBinding(bindingKey
) {
2468 if (!bindingsConsidered
[bindingKey
]) {
2469 var binding
= ko
['getBindingHandler'](bindingKey
);
2471 // First add dependencies (if any) of the current binding
2472 if (binding
['after']) {
2473 cyclicDependencyStack
.push(bindingKey
);
2474 ko
.utils
.arrayForEach(binding
['after'], function(bindingDependencyKey
) {
2475 if (bindings
[bindingDependencyKey
]) {
2476 if (ko
.utils
.arrayIndexOf(cyclicDependencyStack
, bindingDependencyKey
) !== -1) {
2477 throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack
.join(", "));
2479 pushBinding(bindingDependencyKey
);
2483 cyclicDependencyStack
.pop();
2485 // Next add the current binding
2486 result
.push({ key
: bindingKey
, handler
: binding
});
2488 bindingsConsidered
[bindingKey
] = true;
2495 function applyBindingsToNodeInternal(node
, sourceBindings
, bindingContext
, bindingContextMayDifferFromDomParentElement
) {
2496 // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
2497 var alreadyBound
= ko
.utils
.domData
.get(node
, boundElementDomDataKey
);
2498 if (!sourceBindings
) {
2500 throw Error("You cannot apply bindings multiple times to the same element.");
2502 ko
.utils
.domData
.set(node
, boundElementDomDataKey
, true);
2505 // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
2506 // we can easily recover it just by scanning up the node's ancestors in the DOM
2507 // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
2508 if (!alreadyBound
&& bindingContextMayDifferFromDomParentElement
)
2509 ko
.storedBindingContextForNode(node
, bindingContext
);
2511 // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
2513 if (sourceBindings
&& typeof sourceBindings
!== 'function') {
2514 bindings
= sourceBindings
;
2516 var provider
= ko
.bindingProvider
['instance'],
2517 getBindings
= provider
['getBindingAccessors'] || getBindingsAndMakeAccessors
;
2519 if (sourceBindings
|| bindingContext
._subscribable
) {
2520 // When an obsevable view model is used, the binding context will expose an observable _subscribable value.
2521 // Get the binding from the provider within a computed observable so that we can update the bindings whenever
2522 // the binding context is updated.
2523 var bindingsUpdater
= ko
.dependentObservable(
2525 bindings
= sourceBindings
? sourceBindings(bindingContext
, node
) : getBindings
.call(provider
, node
, bindingContext
);
2526 // Register a dependency on the binding context
2527 if (bindings
&& bindingContext
._subscribable
)
2528 bindingContext
._subscribable();
2531 null, { disposeWhenNodeIsRemoved
: node
}
2534 if (!bindings
|| !bindingsUpdater
.isActive())
2535 bindingsUpdater
= null;
2537 bindings
= ko
.dependencyDetection
.ignore(getBindings
, provider
, [node
, bindingContext
]);
2541 var bindingHandlerThatControlsDescendantBindings
;
2543 // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
2544 // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
2545 // the latest binding value and registers a dependency on the binding updater.
2546 var getValueAccessor
= bindingsUpdater
2547 ? function(bindingKey
) {
2549 return evaluateValueAccessor(bindingsUpdater()[bindingKey
]);
2551 } : function(bindingKey
) {
2552 return bindings
[bindingKey
];
2555 // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
2556 function allBindings() {
2557 return ko
.utils
.objectMap(bindingsUpdater
? bindingsUpdater() : bindings
, evaluateValueAccessor
);
2559 // The following is the 3.x allBindings API
2560 allBindings
['get'] = function(key
) {
2561 return bindings
[key
] && evaluateValueAccessor(getValueAccessor(key
));
2563 allBindings
['has'] = function(key
) {
2564 return key
in bindings
;
2567 // First put the bindings into the right order
2568 var orderedBindings
= topologicalSortBindings(bindings
);
2570 // Go through the sorted bindings, calling init and update for each
2571 ko
.utils
.arrayForEach(orderedBindings
, function(bindingKeyAndHandler
) {
2572 // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
2573 // so bindingKeyAndHandler.handler will always be nonnull.
2574 var handlerInitFn
= bindingKeyAndHandler
.handler
["init"],
2575 handlerUpdateFn
= bindingKeyAndHandler
.handler
["update"],
2576 bindingKey
= bindingKeyAndHandler
.key
;
2578 if (node
.nodeType
=== 8) {
2579 validateThatBindingIsAllowedForVirtualElements(bindingKey
);
2583 // Run init, ignoring any dependencies
2584 if (typeof handlerInitFn
== "function") {
2585 ko
.dependencyDetection
.ignore(function() {
2586 var initResult
= handlerInitFn(node
, getValueAccessor(bindingKey
), allBindings
, bindingContext
['$data'], bindingContext
);
2588 // If this binding handler claims to control descendant bindings, make a note of this
2589 if (initResult
&& initResult
['controlsDescendantBindings']) {
2590 if (bindingHandlerThatControlsDescendantBindings
!== undefined)
2591 throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings
+ " and " + bindingKey
+ ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
2592 bindingHandlerThatControlsDescendantBindings
= bindingKey
;
2597 // Run update in its own computed wrapper
2598 if (typeof handlerUpdateFn
== "function") {
2599 ko
.dependentObservable(
2601 handlerUpdateFn(node
, getValueAccessor(bindingKey
), allBindings
, bindingContext
['$data'], bindingContext
);
2604 { disposeWhenNodeIsRemoved
: node
}
2608 ex
.message
= "Unable to process binding \"" + bindingKey
+ ": " + bindings
[bindingKey
] + "\"\nMessage: " + ex
.message
;
2615 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings
=== undefined
2619 var storedBindingContextDomDataKey
= ko
.utils
.domData
.nextKey();
2620 ko
.storedBindingContextForNode = function (node
, bindingContext
) {
2621 if (arguments
.length
== 2) {
2622 ko
.utils
.domData
.set(node
, storedBindingContextDomDataKey
, bindingContext
);
2623 if (bindingContext
._subscribable
)
2624 bindingContext
._subscribable
._addNode(node
);
2626 return ko
.utils
.domData
.get(node
, storedBindingContextDomDataKey
);
2630 function getBindingContext(viewModelOrBindingContext
) {
2631 return viewModelOrBindingContext
&& (viewModelOrBindingContext
instanceof ko
.bindingContext
)
2632 ? viewModelOrBindingContext
2633 : new ko
.bindingContext(viewModelOrBindingContext
);
2636 ko
.applyBindingAccessorsToNode = function (node
, bindings
, viewModelOrBindingContext
) {
2637 if (node
.nodeType
=== 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
2638 ko
.virtualElements
.normaliseVirtualElementDomStructure(node
);
2639 return applyBindingsToNodeInternal(node
, bindings
, getBindingContext(viewModelOrBindingContext
), true);
2642 ko
.applyBindingsToNode = function (node
, bindings
, viewModelOrBindingContext
) {
2643 var context
= getBindingContext(viewModelOrBindingContext
);
2644 return ko
.applyBindingAccessorsToNode(node
, makeBindingAccessors(bindings
, context
, node
), context
);
2647 ko
.applyBindingsToDescendants = function(viewModelOrBindingContext
, rootNode
) {
2648 if (rootNode
.nodeType
=== 1 || rootNode
.nodeType
=== 8)
2649 applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext
), rootNode
, true);
2652 ko
.applyBindings = function (viewModelOrBindingContext
, rootNode
) {
2653 if (rootNode
&& (rootNode
.nodeType
!== 1) && (rootNode
.nodeType
!== 8))
2654 throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
2655 rootNode
= rootNode
|| window
.document
.body
; // Make "rootNode" parameter optional
2657 applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext
), rootNode
, true);
2660 // Retrieving binding context from arbitrary nodes
2661 ko
.contextFor = function(node
) {
2662 // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
2663 switch (node
.nodeType
) {
2666 var context
= ko
.storedBindingContextForNode(node
);
2667 if (context
) return context
;
2668 if (node
.parentNode
) return ko
.contextFor(node
.parentNode
);
2673 ko
.dataFor = function(node
) {
2674 var context
= ko
.contextFor(node
);
2675 return context
? context
['$data'] : undefined;
2678 ko
.exportSymbol('bindingHandlers', ko
.bindingHandlers
);
2679 ko
.exportSymbol('applyBindings', ko
.applyBindings
);
2680 ko
.exportSymbol('applyBindingsToDescendants', ko
.applyBindingsToDescendants
);
2681 ko
.exportSymbol('applyBindingAccessorsToNode', ko
.applyBindingAccessorsToNode
);
2682 ko
.exportSymbol('applyBindingsToNode', ko
.applyBindingsToNode
);
2683 ko
.exportSymbol('contextFor', ko
.contextFor
);
2684 ko
.exportSymbol('dataFor', ko
.dataFor
);
2686 var attrHtmlToJavascriptMap
= { 'class': 'className', 'for': 'htmlFor' };
2687 ko
.bindingHandlers
['attr'] = {
2688 'update': function(element
, valueAccessor
, allBindings
) {
2689 var value
= ko
.utils
.unwrapObservable(valueAccessor()) || {};
2690 ko
.utils
.objectForEach(value
, function(attrName
, attrValue
) {
2691 attrValue
= ko
.utils
.unwrapObservable(attrValue
);
2693 // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
2694 // when someProp is a "no value"-like value (strictly null, false, or undefined)
2695 // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
2696 var toRemove
= (attrValue
=== false) || (attrValue
=== null) || (attrValue
=== undefined);
2698 element
.removeAttribute(attrName
);
2700 // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
2701 // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
2702 // but instead of figuring out the mode, we'll just set the attribute through the Javascript
2703 // property for IE <= 8.
2704 if (ko
.utils
.ieVersion
<= 8 && attrName
in attrHtmlToJavascriptMap
) {
2705 attrName
= attrHtmlToJavascriptMap
[attrName
];
2707 element
.removeAttribute(attrName
);
2709 element
[attrName
] = attrValue
;
2710 } else if (!toRemove
) {
2711 element
.setAttribute(attrName
, attrValue
.toString());
2714 // Treat "name" specially - although you can think of it as an attribute, it also needs
2715 // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
2716 // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
2717 // entirely, and there's no strong reason to allow for such casing in HTML.
2718 if (attrName
=== "name") {
2719 ko
.utils
.setElementName(element
, toRemove
? "" : attrValue
.toString());
2726 ko
.bindingHandlers
['checked'] = {
2727 'after': ['value', 'attr'],
2728 'init': function (element
, valueAccessor
, allBindings
) {
2729 function checkedValue() {
2730 return allBindings
['has']('checkedValue')
2731 ? ko
.utils
.unwrapObservable(allBindings
.get('checkedValue'))
2735 function updateModel() {
2736 // This updates the model value from the view value.
2737 // It runs in response to DOM events (click) and changes in checkedValue.
2738 var isChecked
= element
.checked
,
2739 elemValue
= useCheckedValue
? checkedValue() : isChecked
;
2741 // When we're first setting up this computed, don't change any model state.
2746 // We can ignore unchecked radio buttons, because some other radio
2747 // button will be getting checked, and that one can take care of updating state.
2748 if (isRadio
&& !isChecked
) {
2752 var modelValue
= ko
.dependencyDetection
.ignore(valueAccessor
);
2754 if (oldElemValue
!== elemValue
) {
2755 // When we're responding to the checkedValue changing, and the element is
2756 // currently checked, replace the old elem value with the new elem value
2757 // in the model array.
2759 ko
.utils
.addOrRemoveItem(modelValue
, elemValue
, true);
2760 ko
.utils
.addOrRemoveItem(modelValue
, oldElemValue
, false);
2763 oldElemValue
= elemValue
;
2765 // When we're responding to the user having checked/unchecked a checkbox,
2766 // add/remove the element value to the model array.
2767 ko
.utils
.addOrRemoveItem(modelValue
, elemValue
, isChecked
);
2770 ko
.expressionRewriting
.writeValueToProperty(modelValue
, allBindings
, 'checked', elemValue
, true);
2774 function updateView() {
2775 // This updates the view value from the model value.
2776 // It runs in response to changes in the bound (checked) value.
2777 var modelValue
= ko
.utils
.unwrapObservable(valueAccessor());
2780 // When a checkbox is bound to an array, being checked represents its value being present in that array
2781 element
.checked
= ko
.utils
.arrayIndexOf(modelValue
, checkedValue()) >= 0;
2782 } else if (isCheckbox
) {
2783 // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
2784 element
.checked
= modelValue
;
2786 // For radio buttons, being checked means that the radio button's value corresponds to the model value
2787 element
.checked
= (checkedValue() === modelValue
);
2791 var isCheckbox
= element
.type
== "checkbox",
2792 isRadio
= element
.type
== "radio";
2794 // Only bind to check boxes and radio buttons
2795 if (!isCheckbox
&& !isRadio
) {
2799 var isValueArray
= isCheckbox
&& (ko
.utils
.unwrapObservable(valueAccessor()) instanceof Array
),
2800 oldElemValue
= isValueArray
? checkedValue() : undefined,
2801 useCheckedValue
= isRadio
|| isValueArray
,
2804 // IE 6 won't allow radio buttons to be selected unless they have a name
2805 if (isRadio
&& !element
.name
)
2806 ko
.bindingHandlers
['uniqueName']['init'](element
, function() { return true });
2808 // Set up two computeds to update the binding:
2810 // The first responds to changes in the checkedValue value and to element clicks
2811 ko
.dependentObservable(updateModel
, null, { disposeWhenNodeIsRemoved
: element
});
2812 ko
.utils
.registerEventHandler(element
, "click", updateModel
);
2814 // The second responds to changes in the model value (the one associated with the checked binding)
2815 ko
.dependentObservable(updateView
, null, { disposeWhenNodeIsRemoved
: element
});
2820 ko
.expressionRewriting
.twoWayBindings
['checked'] = true;
2822 ko
.bindingHandlers
['checkedValue'] = {
2823 'update': function (element
, valueAccessor
) {
2824 element
.value
= ko
.utils
.unwrapObservable(valueAccessor());
2828 })();var classesWrittenByBindingKey
= '__ko__cssValue';
2829 ko
.bindingHandlers
['css'] = {
2830 'update': function (element
, valueAccessor
) {
2831 var value
= ko
.utils
.unwrapObservable(valueAccessor());
2832 if (typeof value
== "object") {
2833 ko
.utils
.objectForEach(value
, function(className
, shouldHaveClass
) {
2834 shouldHaveClass
= ko
.utils
.unwrapObservable(shouldHaveClass
);
2835 ko
.utils
.toggleDomNodeCssClass(element
, className
, shouldHaveClass
);
2838 value
= String(value
|| ''); // Make sure we don't try to store or set a non-string value
2839 ko
.utils
.toggleDomNodeCssClass(element
, element
[classesWrittenByBindingKey
], false);
2840 element
[classesWrittenByBindingKey
] = value
;
2841 ko
.utils
.toggleDomNodeCssClass(element
, value
, true);
2845 ko
.bindingHandlers
['enable'] = {
2846 'update': function (element
, valueAccessor
) {
2847 var value
= ko
.utils
.unwrapObservable(valueAccessor());
2848 if (value
&& element
.disabled
)
2849 element
.removeAttribute("disabled");
2850 else if ((!value
) && (!element
.disabled
))
2851 element
.disabled
= true;
2855 ko
.bindingHandlers
['disable'] = {
2856 'update': function (element
, valueAccessor
) {
2857 ko
.bindingHandlers
['enable']['update'](element
, function() { return !ko
.utils
.unwrapObservable(valueAccessor()) });
2860 // For certain common events (currently just 'click'), allow a simplified data-binding syntax
2861 // e.g. click:handler instead of the usual full-length event:{click:handler}
2862 function makeEventHandlerShortcut(eventName
) {
2863 ko
.bindingHandlers
[eventName
] = {
2864 'init': function(element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
2865 var newValueAccessor = function () {
2867 result
[eventName
] = valueAccessor();
2870 return ko
.bindingHandlers
['event']['init'].call(this, element
, newValueAccessor
, allBindings
, viewModel
, bindingContext
);
2875 ko
.bindingHandlers
['event'] = {
2876 'init' : function (element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
2877 var eventsToHandle
= valueAccessor() || {};
2878 ko
.utils
.objectForEach(eventsToHandle
, function(eventName
) {
2879 if (typeof eventName
== "string") {
2880 ko
.utils
.registerEventHandler(element
, eventName
, function (event
) {
2881 var handlerReturnValue
;
2882 var handlerFunction
= valueAccessor()[eventName
];
2883 if (!handlerFunction
)
2887 // Take all the event args, and prefix with the viewmodel
2888 var argsForHandler
= ko
.utils
.makeArray(arguments
);
2889 viewModel
= bindingContext
['$data'];
2890 argsForHandler
.unshift(viewModel
);
2891 handlerReturnValue
= handlerFunction
.apply(viewModel
, argsForHandler
);
2893 if (handlerReturnValue
!== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
2894 if (event
.preventDefault
)
2895 event
.preventDefault();
2897 event
.returnValue
= false;
2901 var bubble
= allBindings
.get(eventName
+ 'Bubble') !== false;
2903 event
.cancelBubble
= true;
2904 if (event
.stopPropagation
)
2905 event
.stopPropagation();
2912 // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
2913 // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
2914 ko
.bindingHandlers
['foreach'] = {
2915 makeTemplateValueAccessor: function(valueAccessor
) {
2917 var modelValue
= valueAccessor(),
2918 unwrappedValue
= ko
.utils
.peekObservable(modelValue
); // Unwrap without setting a dependency here
2920 // If unwrappedValue is the array, pass in the wrapped value on its own
2921 // The value will be unwrapped and tracked within the template binding
2922 // (See https://github.com/SteveSanderson/knockout/issues/523)
2923 if ((!unwrappedValue
) || typeof unwrappedValue
.length
== "number")
2924 return { 'foreach': modelValue
, 'templateEngine': ko
.nativeTemplateEngine
.instance
};
2926 // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
2927 ko
.utils
.unwrapObservable(modelValue
);
2929 'foreach': unwrappedValue
['data'],
2930 'as': unwrappedValue
['as'],
2931 'includeDestroyed': unwrappedValue
['includeDestroyed'],
2932 'afterAdd': unwrappedValue
['afterAdd'],
2933 'beforeRemove': unwrappedValue
['beforeRemove'],
2934 'afterRender': unwrappedValue
['afterRender'],
2935 'beforeMove': unwrappedValue
['beforeMove'],
2936 'afterMove': unwrappedValue
['afterMove'],
2937 'templateEngine': ko
.nativeTemplateEngine
.instance
2941 'init': function(element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
2942 return ko
.bindingHandlers
['template']['init'](element
, ko
.bindingHandlers
['foreach'].makeTemplateValueAccessor(valueAccessor
));
2944 'update': function(element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
2945 return ko
.bindingHandlers
['template']['update'](element
, ko
.bindingHandlers
['foreach'].makeTemplateValueAccessor(valueAccessor
), allBindings
, viewModel
, bindingContext
);
2948 ko
.expressionRewriting
.bindingRewriteValidators
['foreach'] = false; // Can't rewrite control flow bindings
2949 ko
.virtualElements
.allowedBindings
['foreach'] = true;
2950 var hasfocusUpdatingProperty
= '__ko_hasfocusUpdating';
2951 var hasfocusLastValue
= '__ko_hasfocusLastValue';
2952 ko
.bindingHandlers
['hasfocus'] = {
2953 'init': function(element
, valueAccessor
, allBindings
) {
2954 var handleElementFocusChange = function(isFocused
) {
2955 // Where possible, ignore which event was raised and determine focus state using activeElement,
2956 // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
2957 // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
2958 // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
2959 // from calling 'blur()' on the element when it loses focus.
2960 // Discussion at https://github.com/SteveSanderson/knockout/pull/352
2961 element
[hasfocusUpdatingProperty
] = true;
2962 var ownerDoc
= element
.ownerDocument
;
2963 if ("activeElement" in ownerDoc
) {
2966 active
= ownerDoc
.activeElement
;
2968 // IE9 throws if you access activeElement during page load (see issue #703)
2969 active
= ownerDoc
.body
;
2971 isFocused
= (active
=== element
);
2973 var modelValue
= valueAccessor();
2974 ko
.expressionRewriting
.writeValueToProperty(modelValue
, allBindings
, 'hasfocus', isFocused
, true);
2976 //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
2977 element
[hasfocusLastValue
] = isFocused
;
2978 element
[hasfocusUpdatingProperty
] = false;
2980 var handleElementFocusIn
= handleElementFocusChange
.bind(null, true);
2981 var handleElementFocusOut
= handleElementFocusChange
.bind(null, false);
2983 ko
.utils
.registerEventHandler(element
, "focus", handleElementFocusIn
);
2984 ko
.utils
.registerEventHandler(element
, "focusin", handleElementFocusIn
); // For IE
2985 ko
.utils
.registerEventHandler(element
, "blur", handleElementFocusOut
);
2986 ko
.utils
.registerEventHandler(element
, "focusout", handleElementFocusOut
); // For IE
2988 'update': function(element
, valueAccessor
) {
2989 var value
= !!ko
.utils
.unwrapObservable(valueAccessor()); //force boolean to compare with last value
2990 if (!element
[hasfocusUpdatingProperty
] && element
[hasfocusLastValue
] !== value
) {
2991 value
? element
.focus() : element
.blur();
2992 ko
.dependencyDetection
.ignore(ko
.utils
.triggerEvent
, null, [element
, value
? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
2996 ko
.expressionRewriting
.twoWayBindings
['hasfocus'] = true;
2998 ko
.bindingHandlers
['hasFocus'] = ko
.bindingHandlers
['hasfocus']; // Make "hasFocus" an alias
2999 ko
.expressionRewriting
.twoWayBindings
['hasFocus'] = true;
3000 ko
.bindingHandlers
['html'] = {
3001 'init': function() {
3002 // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
3003 return { 'controlsDescendantBindings': true };
3005 'update': function (element
, valueAccessor
) {
3006 // setHtml will unwrap the value if needed
3007 ko
.utils
.setHtml(element
, valueAccessor());
3010 var withIfDomDataKey
= ko
.utils
.domData
.nextKey();
3011 // Makes a binding like with or if
3012 function makeWithIfBinding(bindingKey
, isWith
, isNot
, makeContextCallback
) {
3013 ko
.bindingHandlers
[bindingKey
] = {
3014 'init': function(element
) {
3015 ko
.utils
.domData
.set(element
, withIfDomDataKey
, {});
3016 return { 'controlsDescendantBindings': true };
3018 'update': function(element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
3019 var withIfData
= ko
.utils
.domData
.get(element
, withIfDomDataKey
),
3020 dataValue
= ko
.utils
.unwrapObservable(valueAccessor()),
3021 shouldDisplay
= !isNot
!== !dataValue
, // equivalent to isNot ? !dataValue : !!dataValue
3022 isFirstRender
= !withIfData
.savedNodes
,
3023 needsRefresh
= isFirstRender
|| isWith
|| (shouldDisplay
!== withIfData
.didDisplayOnLastUpdate
);
3026 if (isFirstRender
) {
3027 withIfData
.savedNodes
= ko
.utils
.cloneNodes(ko
.virtualElements
.childNodes(element
), true /* shouldCleanNodes */);
3030 if (shouldDisplay
) {
3031 if (!isFirstRender
) {
3032 ko
.virtualElements
.setDomNodeChildren(element
, ko
.utils
.cloneNodes(withIfData
.savedNodes
));
3034 ko
.applyBindingsToDescendants(makeContextCallback
? makeContextCallback(bindingContext
, dataValue
) : bindingContext
, element
);
3036 ko
.virtualElements
.emptyNode(element
);
3039 withIfData
.didDisplayOnLastUpdate
= shouldDisplay
;
3043 ko
.expressionRewriting
.bindingRewriteValidators
[bindingKey
] = false; // Can't rewrite control flow bindings
3044 ko
.virtualElements
.allowedBindings
[bindingKey
] = true;
3047 // Construct the actual binding handlers
3048 makeWithIfBinding('if');
3049 makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
3050 makeWithIfBinding('with', true /* isWith */, false /* isNot */,
3051 function(bindingContext
, dataValue
) {
3052 return bindingContext
['createChildContext'](dataValue
);
3055 ko
.bindingHandlers
['options'] = {
3056 'init': function(element
) {
3057 if (ko
.utils
.tagNameLower(element
) !== "select")
3058 throw new Error("options binding applies only to SELECT elements");
3060 // Remove all existing <option>s.
3061 while (element
.length
> 0) {
3065 // Ensures that the binding processor doesn't try to bind the options
3066 return { 'controlsDescendantBindings': true };
3068 'update': function (element
, valueAccessor
, allBindings
) {
3069 function selectedOptions() {
3070 return ko
.utils
.arrayFilter(element
.options
, function (node
) { return node
.selected
; });
3073 var selectWasPreviouslyEmpty
= element
.length
== 0;
3074 var previousScrollTop
= (!selectWasPreviouslyEmpty
&& element
.multiple
) ? element
.scrollTop
: null;
3076 var unwrappedArray
= ko
.utils
.unwrapObservable(valueAccessor());
3077 var includeDestroyed
= allBindings
.get('optionsIncludeDestroyed');
3078 var captionPlaceholder
= {};
3080 var previousSelectedValues
;
3081 if (element
.multiple
) {
3082 previousSelectedValues
= ko
.utils
.arrayMap(selectedOptions(), ko
.selectExtensions
.readValue
);
3084 previousSelectedValues
= element
.selectedIndex
>= 0 ? [ ko
.selectExtensions
.readValue(element
.options
[element
.selectedIndex
]) ] : [];
3087 if (unwrappedArray
) {
3088 if (typeof unwrappedArray
.length
== "undefined") // Coerce single value into array
3089 unwrappedArray
= [unwrappedArray
];
3091 // Filter out any entries marked as destroyed
3092 var filteredArray
= ko
.utils
.arrayFilter(unwrappedArray
, function(item
) {
3093 return includeDestroyed
|| item
=== undefined || item
=== null || !ko
.utils
.unwrapObservable(item
['_destroy']);
3096 // If caption is included, add it to the array
3097 if (allBindings
['has']('optionsCaption')) {
3098 captionValue
= ko
.utils
.unwrapObservable(allBindings
.get('optionsCaption'));
3099 // If caption value is null or undefined, don't show a caption
3100 if (captionValue
!== null && captionValue
!== undefined) {
3101 filteredArray
.unshift(captionPlaceholder
);
3105 // If a falsy value is provided (e.g. null), we'll simply empty the select element
3106 unwrappedArray
= [];
3109 function applyToObject(object
, predicate
, defaultValue
) {
3110 var predicateType
= typeof predicate
;
3111 if (predicateType
== "function") // Given a function; run it against the data value
3112 return predicate(object
);
3113 else if (predicateType
== "string") // Given a string; treat it as a property name on the data value
3114 return object
[predicate
];
3115 else // Given no optionsText arg; use the data value itself
3116 return defaultValue
;
3119 // The following functions can run at two different times:
3120 // The first is when the whole array is being updated directly from this binding handler.
3121 // The second is when an observable value for a specific array entry is updated.
3122 // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
3123 var itemUpdate
= false;
3124 function optionForArrayItem(arrayEntry
, index
, oldOptions
) {
3125 if (oldOptions
.length
) {
3126 previousSelectedValues
= oldOptions
[0].selected
? [ ko
.selectExtensions
.readValue(oldOptions
[0]) ] : [];
3129 var option
= document
.createElement("option");
3130 if (arrayEntry
=== captionPlaceholder
) {
3131 ko
.utils
.setTextContent(option
, allBindings
.get('optionsCaption'));
3132 ko
.selectExtensions
.writeValue(option
, undefined);
3134 // Apply a value to the option element
3135 var optionValue
= applyToObject(arrayEntry
, allBindings
.get('optionsValue'), arrayEntry
);
3136 ko
.selectExtensions
.writeValue(option
, ko
.utils
.unwrapObservable(optionValue
));
3138 // Apply some text to the option element
3139 var optionText
= applyToObject(arrayEntry
, allBindings
.get('optionsText'), optionValue
);
3140 ko
.utils
.setTextContent(option
, optionText
);
3145 function setSelectionCallback(arrayEntry
, newOptions
) {
3146 // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
3147 // That's why we first added them without selection. Now it's time to set the selection.
3148 if (previousSelectedValues
.length
) {
3149 var isSelected
= ko
.utils
.arrayIndexOf(previousSelectedValues
, ko
.selectExtensions
.readValue(newOptions
[0])) >= 0;
3150 ko
.utils
.setOptionNodeSelectionState(newOptions
[0], isSelected
);
3152 // If this option was changed from being selected during a single-item update, notify the change
3153 if (itemUpdate
&& !isSelected
)
3154 ko
.dependencyDetection
.ignore(ko
.utils
.triggerEvent
, null, [element
, "change"]);
3158 var callback
= setSelectionCallback
;
3159 if (allBindings
['has']('optionsAfterRender')) {
3160 callback = function(arrayEntry
, newOptions
) {
3161 setSelectionCallback(arrayEntry
, newOptions
);
3162 ko
.dependencyDetection
.ignore(allBindings
.get('optionsAfterRender'), null, [newOptions
[0], arrayEntry
!== captionPlaceholder
? arrayEntry
: undefined]);
3166 ko
.utils
.setDomNodeChildrenFromArrayMapping(element
, filteredArray
, optionForArrayItem
, null, callback
);
3168 // Determine if the selection has changed as a result of updating the options list
3169 var selectionChanged
;
3170 if (element
.multiple
) {
3171 // For a multiple-select box, compare the new selection count to the previous one
3172 // But if nothing was selected before, the selection can't have changed
3173 selectionChanged
= previousSelectedValues
.length
&& selectedOptions().length
< previousSelectedValues
.length
;
3175 // For a single-select box, compare the current value to the previous value
3176 // But if nothing was selected before or nothing is selected now, just look for a change in selection
3177 selectionChanged
= (previousSelectedValues
.length
&& element
.selectedIndex
>= 0)
3178 ? (ko
.selectExtensions
.readValue(element
.options
[element
.selectedIndex
]) !== previousSelectedValues
[0])
3179 : (previousSelectedValues
.length
|| element
.selectedIndex
>= 0);
3182 // Ensure consistency between model value and selected option.
3183 // If the dropdown was changed so that selection is no longer the same,
3184 // notify the value or selectedOptions binding.
3185 if (selectionChanged
)
3186 ko
.dependencyDetection
.ignore(ko
.utils
.triggerEvent
, null, [element
, "change"]);
3188 // Workaround for IE bug
3189 ko
.utils
.ensureSelectElementIsRenderedCorrectly(element
);
3191 if (previousScrollTop
&& Math
.abs(previousScrollTop
- element
.scrollTop
) > 20)
3192 element
.scrollTop
= previousScrollTop
;
3195 ko
.bindingHandlers
['options'].optionValueDomDataKey
= ko
.utils
.domData
.nextKey();
3196 ko
.bindingHandlers
['selectedOptions'] = {
3197 'after': ['options', 'foreach'],
3198 'init': function (element
, valueAccessor
, allBindings
) {
3199 ko
.utils
.registerEventHandler(element
, "change", function () {
3200 var value
= valueAccessor(), valueToWrite
= [];
3201 ko
.utils
.arrayForEach(element
.getElementsByTagName("option"), function(node
) {
3203 valueToWrite
.push(ko
.selectExtensions
.readValue(node
));
3205 ko
.expressionRewriting
.writeValueToProperty(value
, allBindings
, 'selectedOptions', valueToWrite
);
3208 'update': function (element
, valueAccessor
) {
3209 if (ko
.utils
.tagNameLower(element
) != "select")
3210 throw new Error("values binding applies only to SELECT elements");
3212 var newValue
= ko
.utils
.unwrapObservable(valueAccessor());
3213 if (newValue
&& typeof newValue
.length
== "number") {
3214 ko
.utils
.arrayForEach(element
.getElementsByTagName("option"), function(node
) {
3215 var isSelected
= ko
.utils
.arrayIndexOf(newValue
, ko
.selectExtensions
.readValue(node
)) >= 0;
3216 ko
.utils
.setOptionNodeSelectionState(node
, isSelected
);
3221 ko
.expressionRewriting
.twoWayBindings
['selectedOptions'] = true;
3222 ko
.bindingHandlers
['style'] = {
3223 'update': function (element
, valueAccessor
) {
3224 var value
= ko
.utils
.unwrapObservable(valueAccessor() || {});
3225 ko
.utils
.objectForEach(value
, function(styleName
, styleValue
) {
3226 styleValue
= ko
.utils
.unwrapObservable(styleValue
);
3227 element
.style
[styleName
] = styleValue
|| ""; // Empty string removes the value, whereas null/undefined have no effect
3231 ko
.bindingHandlers
['submit'] = {
3232 'init': function (element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
3233 if (typeof valueAccessor() != "function")
3234 throw new Error("The value for a submit binding must be a function");
3235 ko
.utils
.registerEventHandler(element
, "submit", function (event
) {
3236 var handlerReturnValue
;
3237 var value
= valueAccessor();
3238 try { handlerReturnValue
= value
.call(bindingContext
['$data'], element
); }
3240 if (handlerReturnValue
!== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
3241 if (event
.preventDefault
)
3242 event
.preventDefault();
3244 event
.returnValue
= false;
3250 ko
.bindingHandlers
['text'] = {
3251 'init': function() {
3252 // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
3253 // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
3254 return { 'controlsDescendantBindings': true };
3256 'update': function (element
, valueAccessor
) {
3257 ko
.utils
.setTextContent(element
, valueAccessor());
3260 ko
.virtualElements
.allowedBindings
['text'] = true;
3261 ko
.bindingHandlers
['uniqueName'] = {
3262 'init': function (element
, valueAccessor
) {
3263 if (valueAccessor()) {
3264 var name
= "ko_unique_" + (++ko
.bindingHandlers
['uniqueName'].currentIndex
);
3265 ko
.utils
.setElementName(element
, name
);
3269 ko
.bindingHandlers
['uniqueName'].currentIndex
= 0;
3270 ko
.bindingHandlers
['value'] = {
3271 'after': ['options', 'foreach'],
3272 'init': function (element
, valueAccessor
, allBindings
) {
3273 // Always catch "change" event; possibly other events too if asked
3274 var eventsToCatch
= ["change"];
3275 var requestedEventsToCatch
= allBindings
.get("valueUpdate");
3276 var propertyChangedFired
= false;
3277 if (requestedEventsToCatch
) {
3278 if (typeof requestedEventsToCatch
== "string") // Allow both individual event names, and arrays of event names
3279 requestedEventsToCatch
= [requestedEventsToCatch
];
3280 ko
.utils
.arrayPushAll(eventsToCatch
, requestedEventsToCatch
);
3281 eventsToCatch
= ko
.utils
.arrayGetDistinctValues(eventsToCatch
);
3284 var valueUpdateHandler = function() {
3285 propertyChangedFired
= false;
3286 var modelValue
= valueAccessor();
3287 var elementValue
= ko
.selectExtensions
.readValue(element
);
3288 ko
.expressionRewriting
.writeValueToProperty(modelValue
, allBindings
, 'value', elementValue
);
3291 // Workaround for https://github.com/SteveSanderson/knockout/issues/122
3292 // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
3293 var ieAutoCompleteHackNeeded
= ko
.utils
.ieVersion
&& element
.tagName
.toLowerCase() == "input" && element
.type
== "text"
3294 && element
.autocomplete
!= "off" && (!element
.form
|| element
.form
.autocomplete
!= "off");
3295 if (ieAutoCompleteHackNeeded
&& ko
.utils
.arrayIndexOf(eventsToCatch
, "propertychange") == -1) {
3296 ko
.utils
.registerEventHandler(element
, "propertychange", function () { propertyChangedFired
= true });
3297 ko
.utils
.registerEventHandler(element
, "blur", function() {
3298 if (propertyChangedFired
) {
3299 valueUpdateHandler();
3304 ko
.utils
.arrayForEach(eventsToCatch
, function(eventName
) {
3305 // The syntax "after<eventname>" means "run the handler asynchronously after the event"
3306 // This is useful, for example, to catch "keydown" events after the browser has updated the control
3307 // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
3308 var handler
= valueUpdateHandler
;
3309 if (ko
.utils
.stringStartsWith(eventName
, "after")) {
3310 handler = function() { setTimeout(valueUpdateHandler
, 0) };
3311 eventName
= eventName
.substring("after".length
);
3313 ko
.utils
.registerEventHandler(element
, eventName
, handler
);
3316 'update': function (element
, valueAccessor
) {
3317 var valueIsSelectOption
= ko
.utils
.tagNameLower(element
) === "select";
3318 var newValue
= ko
.utils
.unwrapObservable(valueAccessor());
3319 var elementValue
= ko
.selectExtensions
.readValue(element
);
3320 var valueHasChanged
= (newValue
!== elementValue
);
3322 if (valueHasChanged
) {
3323 var applyValueAction = function () { ko
.selectExtensions
.writeValue(element
, newValue
); };
3326 if (valueIsSelectOption
) {
3327 if (newValue
!== ko
.selectExtensions
.readValue(element
)) {
3328 // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
3329 // because you're not allowed to have a model value that disagrees with a visible UI selection.
3330 ko
.dependencyDetection
.ignore(ko
.utils
.triggerEvent
, null, [element
, "change"]);
3332 // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
3333 // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
3334 // to apply the value as well.
3335 setTimeout(applyValueAction
, 0);
3341 ko
.expressionRewriting
.twoWayBindings
['value'] = true;
3342 ko
.bindingHandlers
['visible'] = {
3343 'update': function (element
, valueAccessor
) {
3344 var value
= ko
.utils
.unwrapObservable(valueAccessor());
3345 var isCurrentlyVisible
= !(element
.style
.display
== "none");
3346 if (value
&& !isCurrentlyVisible
)
3347 element
.style
.display
= "";
3348 else if ((!value
) && isCurrentlyVisible
)
3349 element
.style
.display
= "none";
3352 // 'click' is just a shorthand for the usual full-length event:{click:handler}
3353 makeEventHandlerShortcut('click');
3354 // If you want to make a custom template engine,
3356 // [1] Inherit from this class (like ko.nativeTemplateEngine does)
3357 // [2] Override 'renderTemplateSource', supplying a function with this signature:
3359 // function (templateSource, bindingContext, options) {
3360 // // - templateSource.text() is the text of the template you should render
3361 // // - bindingContext.$data is the data you should pass into the template
3362 // // - you might also want to make bindingContext.$parent, bindingContext.$parents,
3363 // // and bindingContext.$root available in the template too
3364 // // - options gives you access to any other properties set on "data-bind: { template: options }"
3366 // // Return value: an array of DOM nodes
3369 // [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
3371 // function (script) {
3372 // // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
3373 // // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
3376 // This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
3377 // If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
3378 // and then you don't need to override 'createJavaScriptEvaluatorBlock'.
3380 ko
.templateEngine = function () { };
3382 ko
.templateEngine
.prototype['renderTemplateSource'] = function (templateSource
, bindingContext
, options
) {
3383 throw new Error("Override renderTemplateSource");
3386 ko
.templateEngine
.prototype['createJavaScriptEvaluatorBlock'] = function (script
) {
3387 throw new Error("Override createJavaScriptEvaluatorBlock");
3390 ko
.templateEngine
.prototype['makeTemplateSource'] = function(template
, templateDocument
) {
3392 if (typeof template
== "string") {
3393 templateDocument
= templateDocument
|| document
;
3394 var elem
= templateDocument
.getElementById(template
);
3396 throw new Error("Cannot find template with ID " + template
);
3397 return new ko
.templateSources
.domElement(elem
);
3398 } else if ((template
.nodeType
== 1) || (template
.nodeType
== 8)) {
3399 // Anonymous template
3400 return new ko
.templateSources
.anonymousTemplate(template
);
3402 throw new Error("Unknown template type: " + template
);
3405 ko
.templateEngine
.prototype['renderTemplate'] = function (template
, bindingContext
, options
, templateDocument
) {
3406 var templateSource
= this['makeTemplateSource'](template
, templateDocument
);
3407 return this['renderTemplateSource'](templateSource
, bindingContext
, options
);
3410 ko
.templateEngine
.prototype['isTemplateRewritten'] = function (template
, templateDocument
) {
3411 // Skip rewriting if requested
3412 if (this['allowTemplateRewriting'] === false)
3414 return this['makeTemplateSource'](template
, templateDocument
)['data']("isRewritten");
3417 ko
.templateEngine
.prototype['rewriteTemplate'] = function (template
, rewriterCallback
, templateDocument
) {
3418 var templateSource
= this['makeTemplateSource'](template
, templateDocument
);
3419 var rewritten
= rewriterCallback(templateSource
['text']());
3420 templateSource
['text'](rewritten
);
3421 templateSource
['data']("isRewritten", true);
3424 ko
.exportSymbol('templateEngine', ko
.templateEngine
);
3426 ko
.templateRewriting
= (function () {
3427 var memoizeDataBindingAttributeSyntaxRegex
= /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
3428 var memoizeVirtualContainerBindingSyntaxRegex
= /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
3430 function validateDataBindValuesForRewriting(keyValueArray
) {
3431 var allValidators
= ko
.expressionRewriting
.bindingRewriteValidators
;
3432 for (var i
= 0; i
< keyValueArray
.length
; i
++) {
3433 var key
= keyValueArray
[i
]['key'];
3434 if (allValidators
.hasOwnProperty(key
)) {
3435 var validator
= allValidators
[key
];
3437 if (typeof validator
=== "function") {
3438 var possibleErrorMessage
= validator(keyValueArray
[i
]['value']);
3439 if (possibleErrorMessage
)
3440 throw new Error(possibleErrorMessage
);
3441 } else if (!validator
) {
3442 throw new Error("This template engine does not support the '" + key
+ "' binding within its templates");
3448 function constructMemoizedTagReplacement(dataBindAttributeValue
, tagToRetain
, nodeName
, templateEngine
) {
3449 var dataBindKeyValueArray
= ko
.expressionRewriting
.parseObjectLiteral(dataBindAttributeValue
);
3450 validateDataBindValuesForRewriting(dataBindKeyValueArray
);
3451 var rewrittenDataBindAttributeValue
= ko
.expressionRewriting
.preProcessBindings(dataBindKeyValueArray
, {'valueAccessors':true});
3453 // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
3454 // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
3455 // extra indirection.
3456 var applyBindingsToNextSiblingScript
=
3457 "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue
+ " } })()},'" + nodeName
.toLowerCase() + "')";
3458 return templateEngine
['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript
) + tagToRetain
;
3462 ensureTemplateIsRewritten: function (template
, templateEngine
, templateDocument
) {
3463 if (!templateEngine
['isTemplateRewritten'](template
, templateDocument
))
3464 templateEngine
['rewriteTemplate'](template
, function (htmlString
) {
3465 return ko
.templateRewriting
.memoizeBindingAttributeSyntax(htmlString
, templateEngine
);
3466 }, templateDocument
);
3469 memoizeBindingAttributeSyntax: function (htmlString
, templateEngine
) {
3470 return htmlString
.replace(memoizeDataBindingAttributeSyntaxRegex
, function () {
3471 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments
[4], /* tagToRetain: */ arguments
[1], /* nodeName: */ arguments
[2], templateEngine
);
3472 }).replace(memoizeVirtualContainerBindingSyntaxRegex
, function() {
3473 return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments
[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine
);
3477 applyMemoizedBindingsToNextSibling: function (bindings
, nodeName
) {
3478 return ko
.memoization
.memoize(function (domNode
, bindingContext
) {
3479 var nodeToBind
= domNode
.nextSibling
;
3480 if (nodeToBind
&& nodeToBind
.nodeName
.toLowerCase() === nodeName
) {
3481 ko
.applyBindingAccessorsToNode(nodeToBind
, bindings
, bindingContext
);
3489 // Exported only because it has to be referenced by string lookup from within rewritten template
3490 ko
.exportSymbol('__tr_ambtns', ko
.templateRewriting
.applyMemoizedBindingsToNextSibling
);
3492 // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
3493 // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
3495 // Two are provided by default:
3496 // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
3497 // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
3498 // without reading/writing the actual element text content, since it will be overwritten
3499 // with the rendered template output.
3500 // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
3501 // Template sources need to have the following functions:
3502 // text() - returns the template text from your storage location
3503 // text(value) - writes the supplied template text to your storage location
3504 // data(key) - reads values stored using data(key, value) - see below
3505 // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
3507 // Optionally, template sources can also have the following functions:
3508 // nodes() - returns a DOM element containing the nodes of this template, where available
3509 // nodes(value) - writes the given DOM element to your storage location
3510 // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
3511 // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
3513 // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
3514 // using and overriding "makeTemplateSource" to return an instance of your custom template source.
3516 ko
.templateSources
= {};
3518 // ---- ko.templateSources.domElement -----
3520 ko
.templateSources
.domElement = function(element
) {
3521 this.domElement
= element
;
3524 ko
.templateSources
.domElement
.prototype['text'] = function(/* valueToWrite */) {
3525 var tagNameLower
= ko
.utils
.tagNameLower(this.domElement
),
3526 elemContentsProperty
= tagNameLower
=== "script" ? "text"
3527 : tagNameLower
=== "textarea" ? "value"
3530 if (arguments
.length
== 0) {
3531 return this.domElement
[elemContentsProperty
];
3533 var valueToWrite
= arguments
[0];
3534 if (elemContentsProperty
=== "innerHTML")
3535 ko
.utils
.setHtml(this.domElement
, valueToWrite
);
3537 this.domElement
[elemContentsProperty
] = valueToWrite
;
3541 var dataDomDataPrefix
= ko
.utils
.domData
.nextKey() + "_";
3542 ko
.templateSources
.domElement
.prototype['data'] = function(key
/*, valueToWrite */) {
3543 if (arguments
.length
=== 1) {
3544 return ko
.utils
.domData
.get(this.domElement
, dataDomDataPrefix
+ key
);
3546 ko
.utils
.domData
.set(this.domElement
, dataDomDataPrefix
+ key
, arguments
[1]);
3550 // ---- ko.templateSources.anonymousTemplate -----
3551 // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
3552 // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
3553 // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
3555 var anonymousTemplatesDomDataKey
= ko
.utils
.domData
.nextKey();
3556 ko
.templateSources
.anonymousTemplate = function(element
) {
3557 this.domElement
= element
;
3559 ko
.templateSources
.anonymousTemplate
.prototype = new ko
.templateSources
.domElement();
3560 ko
.templateSources
.anonymousTemplate
.prototype.constructor = ko
.templateSources
.anonymousTemplate
;
3561 ko
.templateSources
.anonymousTemplate
.prototype['text'] = function(/* valueToWrite */) {
3562 if (arguments
.length
== 0) {
3563 var templateData
= ko
.utils
.domData
.get(this.domElement
, anonymousTemplatesDomDataKey
) || {};
3564 if (templateData
.textData
=== undefined && templateData
.containerData
)
3565 templateData
.textData
= templateData
.containerData
.innerHTML
;
3566 return templateData
.textData
;
3568 var valueToWrite
= arguments
[0];
3569 ko
.utils
.domData
.set(this.domElement
, anonymousTemplatesDomDataKey
, {textData
: valueToWrite
});
3572 ko
.templateSources
.domElement
.prototype['nodes'] = function(/* valueToWrite */) {
3573 if (arguments
.length
== 0) {
3574 var templateData
= ko
.utils
.domData
.get(this.domElement
, anonymousTemplatesDomDataKey
) || {};
3575 return templateData
.containerData
;
3577 var valueToWrite
= arguments
[0];
3578 ko
.utils
.domData
.set(this.domElement
, anonymousTemplatesDomDataKey
, {containerData
: valueToWrite
});
3582 ko
.exportSymbol('templateSources', ko
.templateSources
);
3583 ko
.exportSymbol('templateSources.domElement', ko
.templateSources
.domElement
);
3584 ko
.exportSymbol('templateSources.anonymousTemplate', ko
.templateSources
.anonymousTemplate
);
3587 var _templateEngine
;
3588 ko
.setTemplateEngine = function (templateEngine
) {
3589 if ((templateEngine
!= undefined) && !(templateEngine
instanceof ko
.templateEngine
))
3590 throw new Error("templateEngine must inherit from ko.templateEngine");
3591 _templateEngine
= templateEngine
;
3594 function invokeForEachNodeInContinuousRange(firstNode
, lastNode
, action
) {
3595 var node
, nextInQueue
= firstNode
, firstOutOfRangeNode
= ko
.virtualElements
.nextSibling(lastNode
);
3596 while (nextInQueue
&& ((node
= nextInQueue
) !== firstOutOfRangeNode
)) {
3597 nextInQueue
= ko
.virtualElements
.nextSibling(node
);
3598 action(node
, nextInQueue
);
3602 function activateBindingsOnContinuousNodeArray(continuousNodeArray
, bindingContext
) {
3603 // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
3604 // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
3605 // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
3606 // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
3607 // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
3609 if (continuousNodeArray
.length
) {
3610 var firstNode
= continuousNodeArray
[0],
3611 lastNode
= continuousNodeArray
[continuousNodeArray
.length
- 1],
3612 parentNode
= firstNode
.parentNode
,
3613 provider
= ko
.bindingProvider
['instance'],
3614 preprocessNode
= provider
['preprocessNode'];
3616 if (preprocessNode
) {
3617 invokeForEachNodeInContinuousRange(firstNode
, lastNode
, function(node
, nextNodeInRange
) {
3618 var nodePreviousSibling
= node
.previousSibling
;
3619 var newNodes
= preprocessNode
.call(provider
, node
);
3621 if (node
=== firstNode
)
3622 firstNode
= newNodes
[0] || nextNodeInRange
;
3623 if (node
=== lastNode
)
3624 lastNode
= newNodes
[newNodes
.length
- 1] || nodePreviousSibling
;
3628 // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
3629 // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
3630 // first node needs to be in the array).
3631 continuousNodeArray
.length
= 0;
3632 if (!firstNode
) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
3635 if (firstNode
=== lastNode
) {
3636 continuousNodeArray
.push(firstNode
);
3638 continuousNodeArray
.push(firstNode
, lastNode
);
3639 ko
.utils
.fixUpContinuousNodeArray(continuousNodeArray
, parentNode
);
3643 // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
3644 // whereas a regular applyBindings won't introduce new memoized nodes
3645 invokeForEachNodeInContinuousRange(firstNode
, lastNode
, function(node
) {
3646 if (node
.nodeType
=== 1 || node
.nodeType
=== 8)
3647 ko
.applyBindings(bindingContext
, node
);
3649 invokeForEachNodeInContinuousRange(firstNode
, lastNode
, function(node
) {
3650 if (node
.nodeType
=== 1 || node
.nodeType
=== 8)
3651 ko
.memoization
.unmemoizeDomNodeAndDescendants(node
, [bindingContext
]);
3654 // Make sure any changes done by applyBindings or unmemoize are reflected in the array
3655 ko
.utils
.fixUpContinuousNodeArray(continuousNodeArray
, parentNode
);
3659 function getFirstNodeFromPossibleArray(nodeOrNodeArray
) {
3660 return nodeOrNodeArray
.nodeType
? nodeOrNodeArray
3661 : nodeOrNodeArray
.length
> 0 ? nodeOrNodeArray
[0]
3665 function executeTemplate(targetNodeOrNodeArray
, renderMode
, template
, bindingContext
, options
) {
3666 options
= options
|| {};
3667 var firstTargetNode
= targetNodeOrNodeArray
&& getFirstNodeFromPossibleArray(targetNodeOrNodeArray
);
3668 var templateDocument
= firstTargetNode
&& firstTargetNode
.ownerDocument
;
3669 var templateEngineToUse
= (options
['templateEngine'] || _templateEngine
);
3670 ko
.templateRewriting
.ensureTemplateIsRewritten(template
, templateEngineToUse
, templateDocument
);
3671 var renderedNodesArray
= templateEngineToUse
['renderTemplate'](template
, bindingContext
, options
, templateDocument
);
3673 // Loosely check result is an array of DOM nodes
3674 if ((typeof renderedNodesArray
.length
!= "number") || (renderedNodesArray
.length
> 0 && typeof renderedNodesArray
[0].nodeType
!= "number"))
3675 throw new Error("Template engine must return an array of DOM nodes");
3677 var haveAddedNodesToParent
= false;
3678 switch (renderMode
) {
3679 case "replaceChildren":
3680 ko
.virtualElements
.setDomNodeChildren(targetNodeOrNodeArray
, renderedNodesArray
);
3681 haveAddedNodesToParent
= true;
3684 ko
.utils
.replaceDomNodes(targetNodeOrNodeArray
, renderedNodesArray
);
3685 haveAddedNodesToParent
= true;
3687 case "ignoreTargetNode": break;
3689 throw new Error("Unknown renderMode: " + renderMode
);
3692 if (haveAddedNodesToParent
) {
3693 activateBindingsOnContinuousNodeArray(renderedNodesArray
, bindingContext
);
3694 if (options
['afterRender'])
3695 ko
.dependencyDetection
.ignore(options
['afterRender'], null, [renderedNodesArray
, bindingContext
['$data']]);
3698 return renderedNodesArray
;
3701 ko
.renderTemplate = function (template
, dataOrBindingContext
, options
, targetNodeOrNodeArray
, renderMode
) {
3702 options
= options
|| {};
3703 if ((options
['templateEngine'] || _templateEngine
) == undefined)
3704 throw new Error("Set a template engine before calling renderTemplate");
3705 renderMode
= renderMode
|| "replaceChildren";
3707 if (targetNodeOrNodeArray
) {
3708 var firstTargetNode
= getFirstNodeFromPossibleArray(targetNodeOrNodeArray
);
3710 var whenToDispose = function () { return (!firstTargetNode
) || !ko
.utils
.domNodeIsAttachedToDocument(firstTargetNode
); }; // Passive disposal (on next evaluation)
3711 var activelyDisposeWhenNodeIsRemoved
= (firstTargetNode
&& renderMode
== "replaceNode") ? firstTargetNode
.parentNode
: firstTargetNode
;
3713 return ko
.dependentObservable( // So the DOM is automatically updated when any dependency changes
3715 // Ensure we've got a proper binding context to work with
3716 var bindingContext
= (dataOrBindingContext
&& (dataOrBindingContext
instanceof ko
.bindingContext
))
3717 ? dataOrBindingContext
3718 : new ko
.bindingContext(ko
.utils
.unwrapObservable(dataOrBindingContext
));
3720 // Support selecting template as a function of the data being rendered
3721 var templateName
= typeof(template
) == 'function' ? template(bindingContext
['$data'], bindingContext
) : template
;
3723 var renderedNodesArray
= executeTemplate(targetNodeOrNodeArray
, renderMode
, templateName
, bindingContext
, options
);
3724 if (renderMode
== "replaceNode") {
3725 targetNodeOrNodeArray
= renderedNodesArray
;
3726 firstTargetNode
= getFirstNodeFromPossibleArray(targetNodeOrNodeArray
);
3730 { disposeWhen
: whenToDispose
, disposeWhenNodeIsRemoved
: activelyDisposeWhenNodeIsRemoved
}
3733 // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
3734 return ko
.memoization
.memoize(function (domNode
) {
3735 ko
.renderTemplate(template
, dataOrBindingContext
, options
, domNode
, "replaceNode");
3740 ko
.renderTemplateForEach = function (template
, arrayOrObservableArray
, options
, targetNode
, parentBindingContext
) {
3741 // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
3742 // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
3743 var arrayItemContext
;
3745 // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
3746 var executeTemplateForArrayItem = function (arrayValue
, index
) {
3747 // Support selecting template as a function of the data being rendered
3748 arrayItemContext
= parentBindingContext
['createChildContext'](arrayValue
, options
['as'], function(context
) {
3749 context
['$index'] = index
;
3751 var templateName
= typeof(template
) == 'function' ? template(arrayValue
, arrayItemContext
) : template
;
3752 return executeTemplate(null, "ignoreTargetNode", templateName
, arrayItemContext
, options
);
3755 // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
3756 var activateBindingsCallback = function(arrayValue
, addedNodesArray
, index
) {
3757 activateBindingsOnContinuousNodeArray(addedNodesArray
, arrayItemContext
);
3758 if (options
['afterRender'])
3759 options
['afterRender'](addedNodesArray
, arrayValue
);
3762 return ko
.dependentObservable(function () {
3763 var unwrappedArray
= ko
.utils
.unwrapObservable(arrayOrObservableArray
) || [];
3764 if (typeof unwrappedArray
.length
== "undefined") // Coerce single value into array
3765 unwrappedArray
= [unwrappedArray
];
3767 // Filter out any entries marked as destroyed
3768 var filteredArray
= ko
.utils
.arrayFilter(unwrappedArray
, function(item
) {
3769 return options
['includeDestroyed'] || item
=== undefined || item
=== null || !ko
.utils
.unwrapObservable(item
['_destroy']);
3772 // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
3773 // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
3774 ko
.dependencyDetection
.ignore(ko
.utils
.setDomNodeChildrenFromArrayMapping
, null, [targetNode
, filteredArray
, executeTemplateForArrayItem
, options
, activateBindingsCallback
]);
3776 }, null, { disposeWhenNodeIsRemoved
: targetNode
});
3779 var templateComputedDomDataKey
= ko
.utils
.domData
.nextKey();
3780 function disposeOldComputedAndStoreNewOne(element
, newComputed
) {
3781 var oldComputed
= ko
.utils
.domData
.get(element
, templateComputedDomDataKey
);
3782 if (oldComputed
&& (typeof(oldComputed
.dispose
) == 'function'))
3783 oldComputed
.dispose();
3784 ko
.utils
.domData
.set(element
, templateComputedDomDataKey
, (newComputed
&& newComputed
.isActive()) ? newComputed
: undefined);
3787 ko
.bindingHandlers
['template'] = {
3788 'init': function(element
, valueAccessor
) {
3789 // Support anonymous templates
3790 var bindingValue
= ko
.utils
.unwrapObservable(valueAccessor());
3791 if (typeof bindingValue
== "string" || bindingValue
['name']) {
3792 // It's a named template - clear the element
3793 ko
.virtualElements
.emptyNode(element
);
3795 // It's an anonymous template - store the element contents, then clear the element
3796 var templateNodes
= ko
.virtualElements
.childNodes(element
),
3797 container
= ko
.utils
.moveCleanedNodesToContainerElement(templateNodes
); // This also removes the nodes from their current parent
3798 new ko
.templateSources
.anonymousTemplate(element
)['nodes'](container
);
3800 return { 'controlsDescendantBindings': true };
3802 'update': function (element
, valueAccessor
, allBindings
, viewModel
, bindingContext
) {
3803 var templateName
= ko
.utils
.unwrapObservable(valueAccessor()),
3805 shouldDisplay
= true,
3807 templateComputed
= null;
3809 if (typeof templateName
!= "string") {
3810 options
= templateName
;
3811 templateName
= ko
.utils
.unwrapObservable(options
['name']);
3813 // Support "if"/"ifnot" conditions
3814 if ('if' in options
)
3815 shouldDisplay
= ko
.utils
.unwrapObservable(options
['if']);
3816 if (shouldDisplay
&& 'ifnot' in options
)
3817 shouldDisplay
= !ko
.utils
.unwrapObservable(options
['ifnot']);
3819 dataValue
= ko
.utils
.unwrapObservable(options
['data']);
3822 if ('foreach' in options
) {
3823 // Render once for each data point (treating data set as empty if shouldDisplay==false)
3824 var dataArray
= (shouldDisplay
&& options
['foreach']) || [];
3825 templateComputed
= ko
.renderTemplateForEach(templateName
|| element
, dataArray
, options
, element
, bindingContext
);
3826 } else if (!shouldDisplay
) {
3827 ko
.virtualElements
.emptyNode(element
);
3829 // Render once for this single data point (or use the viewModel if no data was provided)
3830 var innerBindingContext
= ('data' in options
) ?
3831 bindingContext
['createChildContext'](dataValue
, options
['as']) : // Given an explitit 'data' value, we create a child binding context for it
3832 bindingContext
; // Given no explicit 'data' value, we retain the same binding context
3833 templateComputed
= ko
.renderTemplate(templateName
|| element
, innerBindingContext
, options
, element
);
3836 // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
3837 disposeOldComputedAndStoreNewOne(element
, templateComputed
);
3841 // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
3842 ko
.expressionRewriting
.bindingRewriteValidators
['template'] = function(bindingValue
) {
3843 var parsedBindingValue
= ko
.expressionRewriting
.parseObjectLiteral(bindingValue
);
3845 if ((parsedBindingValue
.length
== 1) && parsedBindingValue
[0]['unknown'])
3846 return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
3848 if (ko
.expressionRewriting
.keyValueArrayContainsKey(parsedBindingValue
, "name"))
3849 return null; // Named templates can be rewritten, so return "no error"
3850 return "This template engine does not support anonymous templates nested within its templates";
3853 ko
.virtualElements
.allowedBindings
['template'] = true;
3856 ko
.exportSymbol('setTemplateEngine', ko
.setTemplateEngine
);
3857 ko
.exportSymbol('renderTemplate', ko
.renderTemplate
);
3859 ko
.utils
.compareArrays
= (function () {
3860 var statusNotInOld
= 'added', statusNotInNew
= 'deleted';
3862 // Simple calculation based on Levenshtein distance.
3863 function compareArrays(oldArray
, newArray
, options
) {
3864 // For backward compatibility, if the third arg is actually a bool, interpret
3865 // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
3866 options
= (typeof options
=== 'boolean') ? { 'dontLimitMoves': options
} : (options
|| {});
3867 oldArray
= oldArray
|| [];
3868 newArray
= newArray
|| [];
3870 if (oldArray
.length
<= newArray
.length
)
3871 return compareSmallArrayToBigArray(oldArray
, newArray
, statusNotInOld
, statusNotInNew
, options
);
3873 return compareSmallArrayToBigArray(newArray
, oldArray
, statusNotInNew
, statusNotInOld
, options
);
3876 function compareSmallArrayToBigArray(smlArray
, bigArray
, statusNotInSml
, statusNotInBig
, options
) {
3877 var myMin
= Math
.min
,
3879 editDistanceMatrix
= [],
3880 smlIndex
, smlIndexMax
= smlArray
.length
,
3881 bigIndex
, bigIndexMax
= bigArray
.length
,
3882 compareRange
= (bigIndexMax
- smlIndexMax
) || 1,
3883 maxDistance
= smlIndexMax
+ bigIndexMax
+ 1,
3885 bigIndexMaxForRow
, bigIndexMinForRow
;
3887 for (smlIndex
= 0; smlIndex
<= smlIndexMax
; smlIndex
++) {
3889 editDistanceMatrix
.push(thisRow
= []);
3890 bigIndexMaxForRow
= myMin(bigIndexMax
, smlIndex
+ compareRange
);
3891 bigIndexMinForRow
= myMax(0, smlIndex
- 1);
3892 for (bigIndex
= bigIndexMinForRow
; bigIndex
<= bigIndexMaxForRow
; bigIndex
++) {
3894 thisRow
[bigIndex
] = smlIndex
+ 1;
3895 else if (!smlIndex
) // Top row - transform empty array into new array via additions
3896 thisRow
[bigIndex
] = bigIndex
+ 1;
3897 else if (smlArray
[smlIndex
- 1] === bigArray
[bigIndex
- 1])
3898 thisRow
[bigIndex
] = lastRow
[bigIndex
- 1]; // copy value (no edit)
3900 var northDistance
= lastRow
[bigIndex
] || maxDistance
; // not in big (deletion)
3901 var westDistance
= thisRow
[bigIndex
- 1] || maxDistance
; // not in small (addition)
3902 thisRow
[bigIndex
] = myMin(northDistance
, westDistance
) + 1;
3907 var editScript
= [], meMinusOne
, notInSml
= [], notInBig
= [];
3908 for (smlIndex
= smlIndexMax
, bigIndex
= bigIndexMax
; smlIndex
|| bigIndex
;) {
3909 meMinusOne
= editDistanceMatrix
[smlIndex
][bigIndex
] - 1;
3910 if (bigIndex
&& meMinusOne
=== editDistanceMatrix
[smlIndex
][bigIndex
-1]) {
3911 notInSml
.push(editScript
[editScript
.length
] = { // added
3912 'status': statusNotInSml
,
3913 'value': bigArray
[--bigIndex
],
3914 'index': bigIndex
});
3915 } else if (smlIndex
&& meMinusOne
=== editDistanceMatrix
[smlIndex
- 1][bigIndex
]) {
3916 notInBig
.push(editScript
[editScript
.length
] = { // deleted
3917 'status': statusNotInBig
,
3918 'value': smlArray
[--smlIndex
],
3919 'index': smlIndex
});
3923 if (!options
['sparse']) {
3925 'status': "retained",
3926 'value': bigArray
[bigIndex
] });
3931 if (notInSml
.length
&& notInBig
.length
) {
3932 // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
3933 // smlIndexMax keeps the time complexity of this algorithm linear.
3934 var limitFailedCompares
= smlIndexMax
* 10, failedCompares
,
3935 a
, d
, notInSmlItem
, notInBigItem
;
3936 // Go through the items that have been added and deleted and try to find matches between them.
3937 for (failedCompares
= a
= 0; (options
['dontLimitMoves'] || failedCompares
< limitFailedCompares
) && (notInSmlItem
= notInSml
[a
]); a
++) {
3938 for (d
= 0; notInBigItem
= notInBig
[d
]; d
++) {
3939 if (notInSmlItem
['value'] === notInBigItem
['value']) {
3940 notInSmlItem
['moved'] = notInBigItem
['index'];
3941 notInBigItem
['moved'] = notInSmlItem
['index'];
3942 notInBig
.splice(d
,1); // This item is marked as moved; so remove it from notInBig list
3943 failedCompares
= d
= 0; // Reset failed compares count because we're checking for consecutive failures
3947 failedCompares
+= d
;
3950 return editScript
.reverse();
3953 return compareArrays
;
3956 ko
.exportSymbol('utils.compareArrays', ko
.utils
.compareArrays
);
3960 // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
3961 // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
3962 // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
3963 // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
3964 // previously mapped - retain those nodes, and just insert/delete other ones
3966 // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
3967 // You can use this, for example, to activate bindings on those nodes.
3969 function mapNodeAndRefreshWhenChanged(containerNode
, mapping
, valueToMap
, callbackAfterAddingNodes
, index
) {
3970 // Map this array value inside a dependentObservable so we re-map when any dependency changes
3971 var mappedNodes
= [];
3972 var dependentObservable
= ko
.dependentObservable(function() {
3973 var newMappedNodes
= mapping(valueToMap
, index
, ko
.utils
.fixUpContinuousNodeArray(mappedNodes
, containerNode
)) || [];
3975 // On subsequent evaluations, just replace the previously-inserted DOM nodes
3976 if (mappedNodes
.length
> 0) {
3977 ko
.utils
.replaceDomNodes(mappedNodes
, newMappedNodes
);
3978 if (callbackAfterAddingNodes
)
3979 ko
.dependencyDetection
.ignore(callbackAfterAddingNodes
, null, [valueToMap
, newMappedNodes
, index
]);
3982 // Replace the contents of the mappedNodes array, thereby updating the record
3983 // of which nodes would be deleted if valueToMap was itself later removed
3984 mappedNodes
.splice(0, mappedNodes
.length
);
3985 ko
.utils
.arrayPushAll(mappedNodes
, newMappedNodes
);
3986 }, null, { disposeWhenNodeIsRemoved
: containerNode
, disposeWhen: function() { return !ko
.utils
.anyDomNodeIsAttachedToDocument(mappedNodes
); } });
3987 return { mappedNodes
: mappedNodes
, dependentObservable
: (dependentObservable
.isActive() ? dependentObservable
: undefined) };
3990 var lastMappingResultDomDataKey
= ko
.utils
.domData
.nextKey();
3992 ko
.utils
.setDomNodeChildrenFromArrayMapping = function (domNode
, array
, mapping
, options
, callbackAfterAddingNodes
) {
3993 // Compare the provided array against the previous one
3994 array
= array
|| [];
3995 options
= options
|| {};
3996 var isFirstExecution
= ko
.utils
.domData
.get(domNode
, lastMappingResultDomDataKey
) === undefined;
3997 var lastMappingResult
= ko
.utils
.domData
.get(domNode
, lastMappingResultDomDataKey
) || [];
3998 var lastArray
= ko
.utils
.arrayMap(lastMappingResult
, function (x
) { return x
.arrayEntry
; });
3999 var editScript
= ko
.utils
.compareArrays(lastArray
, array
, options
['dontLimitMoves']);
4001 // Build the new mapping result
4002 var newMappingResult
= [];
4003 var lastMappingResultIndex
= 0;
4004 var newMappingResultIndex
= 0;
4006 var nodesToDelete
= [];
4007 var itemsToProcess
= [];
4008 var itemsForBeforeRemoveCallbacks
= [];
4009 var itemsForMoveCallbacks
= [];
4010 var itemsForAfterAddCallbacks
= [];
4013 function itemMovedOrRetained(editScriptIndex
, oldPosition
) {
4014 mapData
= lastMappingResult
[oldPosition
];
4015 if (newMappingResultIndex
!== oldPosition
)
4016 itemsForMoveCallbacks
[editScriptIndex
] = mapData
;
4017 // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
4018 mapData
.indexObservable(newMappingResultIndex
++);
4019 ko
.utils
.fixUpContinuousNodeArray(mapData
.mappedNodes
, domNode
);
4020 newMappingResult
.push(mapData
);
4021 itemsToProcess
.push(mapData
);
4024 function callCallback(callback
, items
) {
4026 for (var i
= 0, n
= items
.length
; i
< n
; i
++) {
4028 ko
.utils
.arrayForEach(items
[i
].mappedNodes
, function(node
) {
4029 callback(node
, i
, items
[i
].arrayEntry
);
4036 for (var i
= 0, editScriptItem
, movedIndex
; editScriptItem
= editScript
[i
]; i
++) {
4037 movedIndex
= editScriptItem
['moved'];
4038 switch (editScriptItem
['status']) {
4040 if (movedIndex
=== undefined) {
4041 mapData
= lastMappingResult
[lastMappingResultIndex
];
4043 // Stop tracking changes to the mapping for these nodes
4044 if (mapData
.dependentObservable
)
4045 mapData
.dependentObservable
.dispose();
4047 // Queue these nodes for later removal
4048 nodesToDelete
.push
.apply(nodesToDelete
, ko
.utils
.fixUpContinuousNodeArray(mapData
.mappedNodes
, domNode
));
4049 if (options
['beforeRemove']) {
4050 itemsForBeforeRemoveCallbacks
[i
] = mapData
;
4051 itemsToProcess
.push(mapData
);
4054 lastMappingResultIndex
++;
4058 itemMovedOrRetained(i
, lastMappingResultIndex
++);
4062 if (movedIndex
!== undefined) {
4063 itemMovedOrRetained(i
, movedIndex
);
4065 mapData
= { arrayEntry
: editScriptItem
['value'], indexObservable
: ko
.observable(newMappingResultIndex
++) };
4066 newMappingResult
.push(mapData
);
4067 itemsToProcess
.push(mapData
);
4068 if (!isFirstExecution
)
4069 itemsForAfterAddCallbacks
[i
] = mapData
;
4075 // Call beforeMove first before any changes have been made to the DOM
4076 callCallback(options
['beforeMove'], itemsForMoveCallbacks
);
4078 // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
4079 ko
.utils
.arrayForEach(nodesToDelete
, options
['beforeRemove'] ? ko
.cleanNode
: ko
.removeNode
);
4081 // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
4082 for (var i
= 0, nextNode
= ko
.virtualElements
.firstChild(domNode
), lastNode
, node
; mapData
= itemsToProcess
[i
]; i
++) {
4083 // Get nodes for newly added items
4084 if (!mapData
.mappedNodes
)
4085 ko
.utils
.extend(mapData
, mapNodeAndRefreshWhenChanged(domNode
, mapping
, mapData
.arrayEntry
, callbackAfterAddingNodes
, mapData
.indexObservable
));
4087 // Put nodes in the right place if they aren't there already
4088 for (var j
= 0; node
= mapData
.mappedNodes
[j
]; nextNode
= node
.nextSibling
, lastNode
= node
, j
++) {
4089 if (node
!== nextNode
)
4090 ko
.virtualElements
.insertAfter(domNode
, node
, lastNode
);
4093 // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
4094 if (!mapData
.initialized
&& callbackAfterAddingNodes
) {
4095 callbackAfterAddingNodes(mapData
.arrayEntry
, mapData
.mappedNodes
, mapData
.indexObservable
);
4096 mapData
.initialized
= true;
4100 // If there's a beforeRemove callback, call it after reordering.
4101 // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
4102 // some sort of animation, which is why we first reorder the nodes that will be removed. If the
4103 // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
4104 // Perhaps we'll make that change in the future if this scenario becomes more common.
4105 callCallback(options
['beforeRemove'], itemsForBeforeRemoveCallbacks
);
4107 // Finally call afterMove and afterAdd callbacks
4108 callCallback(options
['afterMove'], itemsForMoveCallbacks
);
4109 callCallback(options
['afterAdd'], itemsForAfterAddCallbacks
);
4111 // Store a copy of the array items we just considered so we can difference it next time
4112 ko
.utils
.domData
.set(domNode
, lastMappingResultDomDataKey
, newMappingResult
);
4116 ko
.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko
.utils
.setDomNodeChildrenFromArrayMapping
);
4117 ko
.nativeTemplateEngine = function () {
4118 this['allowTemplateRewriting'] = false;
4121 ko
.nativeTemplateEngine
.prototype = new ko
.templateEngine();
4122 ko
.nativeTemplateEngine
.prototype.constructor = ko
.nativeTemplateEngine
;
4123 ko
.nativeTemplateEngine
.prototype['renderTemplateSource'] = function (templateSource
, bindingContext
, options
) {
4124 var useNodesIfAvailable
= !(ko
.utils
.ieVersion
< 9), // IE<9 cloneNode doesn't work properly
4125 templateNodesFunc
= useNodesIfAvailable
? templateSource
['nodes'] : null,
4126 templateNodes
= templateNodesFunc
? templateSource
['nodes']() : null;
4128 if (templateNodes
) {
4129 return ko
.utils
.makeArray(templateNodes
.cloneNode(true).childNodes
);
4131 var templateText
= templateSource
['text']();
4132 return ko
.utils
.parseHtmlFragment(templateText
);
4136 ko
.nativeTemplateEngine
.instance
= new ko
.nativeTemplateEngine();
4137 ko
.setTemplateEngine(ko
.nativeTemplateEngine
.instance
);
4139 ko
.exportSymbol('nativeTemplateEngine', ko
.nativeTemplateEngine
);
4141 ko
.jqueryTmplTemplateEngine = function () {
4142 // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
4143 // doesn't expose a version number, so we have to infer it.
4144 // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
4145 // which KO internally refers to as version "2", so older versions are no longer detected.
4146 var jQueryTmplVersion
= this.jQueryTmplVersion
= (function() {
4147 if ((typeof(jQuery
) == "undefined") || !(jQuery
['tmpl']))
4149 // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
4151 if (jQuery
['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
4152 // Since 1.0.0pre, custom tags should append markup to an array called "__"
4153 return 2; // Final version of jquery.tmpl
4155 } catch(ex
) { /* Apparently not the version we were looking for */ }
4157 return 1; // Any older version that we don't support
4160 function ensureHasReferencedJQueryTemplates() {
4161 if (jQueryTmplVersion
< 2)
4162 throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
4165 function executeTemplate(compiledTemplate
, data
, jQueryTemplateOptions
) {
4166 return jQuery
['tmpl'](compiledTemplate
, data
, jQueryTemplateOptions
);
4169 this['renderTemplateSource'] = function(templateSource
, bindingContext
, options
) {
4170 options
= options
|| {};
4171 ensureHasReferencedJQueryTemplates();
4173 // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
4174 var precompiled
= templateSource
['data']('precompiled');
4176 var templateText
= templateSource
['text']() || "";
4177 // Wrap in "with($whatever.koBindingContext) { ... }"
4178 templateText
= "{{ko_with $item.koBindingContext}}" + templateText
+ "{{/ko_with}}";
4180 precompiled
= jQuery
['template'](null, templateText
);
4181 templateSource
['data']('precompiled', precompiled
);
4184 var data
= [bindingContext
['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
4185 var jQueryTemplateOptions
= jQuery
['extend']({ 'koBindingContext': bindingContext
}, options
['templateOptions']);
4187 var resultNodes
= executeTemplate(precompiled
, data
, jQueryTemplateOptions
);
4188 resultNodes
['appendTo'](document
.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
4190 jQuery
['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
4194 this['createJavaScriptEvaluatorBlock'] = function(script
) {
4195 return "{{ko_code ((function() { return " + script
+ " })()) }}";
4198 this['addTemplate'] = function(templateName
, templateMarkup
) {
4199 document
.write("<script type='text/html' id='" + templateName
+ "'>" + templateMarkup
+ "<" + "/script>");
4202 if (jQueryTmplVersion
> 0) {
4203 jQuery
['tmpl']['tag']['ko_code'] = {
4204 open
: "__.push($1 || '');"
4206 jQuery
['tmpl']['tag']['ko_with'] = {
4213 ko
.jqueryTmplTemplateEngine
.prototype = new ko
.templateEngine();
4214 ko
.jqueryTmplTemplateEngine
.prototype.constructor = ko
.jqueryTmplTemplateEngine
;
4216 // Use this one by default *only if jquery.tmpl is referenced*
4217 var jqueryTmplTemplateEngineInstance
= new ko
.jqueryTmplTemplateEngine();
4218 if (jqueryTmplTemplateEngineInstance
.jQueryTmplVersion
> 0)
4219 ko
.setTemplateEngine(jqueryTmplTemplateEngineInstance
);
4221 ko
.exportSymbol('jqueryTmplTemplateEngine', ko
.jqueryTmplTemplateEngine
);