1.1 --- a/ko/bck2brwsr/pom.xml Mon Jan 06 13:45:57 2014 +0100
1.2 +++ b/ko/bck2brwsr/pom.xml Wed Jan 08 14:06:21 2014 +0100
1.3 @@ -62,6 +62,12 @@
1.4 <version>${project.version}</version>
1.5 <type>jar</type>
1.6 <scope>test</scope>
1.7 + <exclusions>
1.8 + <exclusion>
1.9 + <artifactId>json</artifactId>
1.10 + <groupId>org.json</groupId>
1.11 + </exclusion>
1.12 + </exclusions>
1.13 </dependency>
1.14 <dependency>
1.15 <groupId>org.apidesign.bck2brwsr</groupId>
1.16 @@ -74,6 +80,12 @@
1.17 <artifactId>launcher.http</artifactId>
1.18 <version>${project.version}</version>
1.19 <scope>test</scope>
1.20 + <exclusions>
1.21 + <exclusion>
1.22 + <artifactId>asm</artifactId>
1.23 + <groupId>org.ow2.asm</groupId>
1.24 + </exclusion>
1.25 + </exclusions>
1.26 </dependency>
1.27 <dependency>
1.28 <groupId>org.netbeans.html</groupId>
1.29 @@ -97,6 +109,27 @@
1.30 <artifactId>net.java.html.boot</artifactId>
1.31 <version>${net.java.html.version}</version>
1.32 <type>jar</type>
1.33 + <exclusions>
1.34 + <exclusion>
1.35 + <artifactId>asm</artifactId>
1.36 + <groupId>org.ow2.asm</groupId>
1.37 + </exclusion>
1.38 + </exclusions>
1.39 + </dependency>
1.40 + <dependency>
1.41 + <groupId>org.netbeans.html</groupId>
1.42 + <artifactId>ko-fx</artifactId>
1.43 + <version>0.7-SNAPSHOT</version>
1.44 + <exclusions>
1.45 + <exclusion>
1.46 + <artifactId>json</artifactId>
1.47 + <groupId>org.json</groupId>
1.48 + </exclusion>
1.49 + <exclusion>
1.50 + <artifactId>org.json-osgi</artifactId>
1.51 + <groupId>de.twentyeleven.skysail</groupId>
1.52 + </exclusion>
1.53 + </exclusions>
1.54 </dependency>
1.55 </dependencies>
1.56 </project>
2.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/BrwsrCtxImpl.java Mon Jan 06 13:45:57 2014 +0100
2.2 +++ b/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/BrwsrCtxImpl.java Wed Jan 08 14:06:21 2014 +0100
2.3 @@ -21,10 +21,7 @@
2.4 import java.io.IOException;
2.5 import java.io.InputStream;
2.6 import java.io.InputStreamReader;
2.7 -import org.apidesign.html.json.spi.FunctionBinding;
2.8 import org.apidesign.html.json.spi.JSONCall;
2.9 -import org.apidesign.html.json.spi.PropertyBinding;
2.10 -import org.apidesign.html.json.spi.Technology;
2.11 import org.apidesign.html.json.spi.Transfer;
2.12 import org.apidesign.html.json.spi.WSTransfer;
2.13
2.14 @@ -32,7 +29,7 @@
2.15 *
2.16 * @author Jaroslav Tulach <jtulach@netbeans.org>
2.17 */
2.18 -final class BrwsrCtxImpl implements Technology<Object>, Transfer, WSTransfer<LoadWS> {
2.19 +final class BrwsrCtxImpl implements Transfer, WSTransfer<LoadWS> {
2.20 private BrwsrCtxImpl() {}
2.21
2.22 public static final BrwsrCtxImpl DEFAULT = new BrwsrCtxImpl();
2.23 @@ -92,45 +89,6 @@
2.24 }
2.25
2.26 @Override
2.27 - public Object wrapModel(Object model) {
2.28 - return model;
2.29 - }
2.30 -
2.31 - @Override
2.32 - public void bind(PropertyBinding b, Object model, Object data) {
2.33 - Knockout.bind(data, b, b.getPropertyName(),
2.34 - "getValue__Ljava_lang_Object_2",
2.35 - b.isReadOnly() ? null : "setValue__VLjava_lang_Object_2",
2.36 - false, false
2.37 - );
2.38 - }
2.39 -
2.40 - @Override
2.41 - public void valueHasMutated(Object data, String propertyName) {
2.42 - Knockout.valueHasMutated(data, propertyName);
2.43 - }
2.44 -
2.45 - @Override
2.46 - public void expose(FunctionBinding fb, Object model, Object d) {
2.47 - Knockout.expose(d, fb, fb.getFunctionName(), "call__VLjava_lang_Object_2Ljava_lang_Object_2");
2.48 - }
2.49 -
2.50 - @Override
2.51 - public void applyBindings(Object data) {
2.52 - Knockout.applyBindings(data);
2.53 - }
2.54 -
2.55 - @Override
2.56 - public Object wrapArray(Object[] arr) {
2.57 - return arr;
2.58 - }
2.59 -
2.60 - @Override
2.61 - public <M> M toModel(Class<M> modelClass, Object data) {
2.62 - return modelClass.cast(data);
2.63 - }
2.64 -
2.65 - @Override
2.66 public Object toJSON(InputStream is) throws IOException {
2.67 StringBuilder sb = new StringBuilder();
2.68 InputStreamReader r = new InputStreamReader(is);
2.69 @@ -145,11 +103,6 @@
2.70 }
2.71
2.72 @Override
2.73 - public void runSafe(Runnable r) {
2.74 - r.run();
2.75 - }
2.76 -
2.77 - @Override
2.78 public LoadWS open(String url, JSONCall callback) {
2.79 return new LoadWS(callback, url);
2.80 }
3.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/BrwsrCtxPrvdr.java Mon Jan 06 13:45:57 2014 +0100
3.2 +++ b/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/BrwsrCtxPrvdr.java Wed Jan 08 14:06:21 2014 +0100
3.3 @@ -40,9 +40,9 @@
3.4 @Override
3.5 public void fillContext(Contexts.Builder context, Class<?> requestor) {
3.6 if (bck2BrwsrVM()) {
3.7 - context.register(Technology.class, BrwsrCtxImpl.DEFAULT, 50).
3.8 - register(Transfer.class, BrwsrCtxImpl.DEFAULT, 50).
3.9 - register(WSTransfer.class, BrwsrCtxImpl.DEFAULT, 50);
3.10 + context.
3.11 + register(Transfer.class, BrwsrCtxImpl.DEFAULT, 50).
3.12 + register(WSTransfer.class, BrwsrCtxImpl.DEFAULT, 50);
3.13 }
3.14 }
3.15
4.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/Knockout.java Mon Jan 06 13:45:57 2014 +0100
4.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
4.3 @@ -1,131 +0,0 @@
4.4 -/**
4.5 - * Back 2 Browser Bytecode Translator
4.6 - * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
4.7 - *
4.8 - * This program is free software: you can redistribute it and/or modify
4.9 - * it under the terms of the GNU General Public License as published by
4.10 - * the Free Software Foundation, version 2 of the License.
4.11 - *
4.12 - * This program is distributed in the hope that it will be useful,
4.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
4.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4.15 - * GNU General Public License for more details.
4.16 - *
4.17 - * You should have received a copy of the GNU General Public License
4.18 - * along with this program. Look for COPYING file in the top folder.
4.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
4.20 - */
4.21 -package org.apidesign.bck2brwsr.ko2brwsr;
4.22 -
4.23 -import java.lang.reflect.Method;
4.24 -import java.util.List;
4.25 -import org.apidesign.bck2brwsr.core.ExtraJavaScript;
4.26 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
4.27 -
4.28 -/** Provides binding between models and bck2brwsr VM.
4.29 - *
4.30 - * @author Jaroslav Tulach <jtulach@netbeans.org>
4.31 - */
4.32 -@ExtraJavaScript(resource = "/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js")
4.33 -final class Knockout {
4.34 - /** used by tests */
4.35 - static Knockout next;
4.36 - private final Object model;
4.37 -
4.38 - Knockout(Object model) {
4.39 - this.model = model == null ? this : model;
4.40 - }
4.41 -
4.42 - public static <M> Knockout applyBindings(
4.43 - Object model, String[] propsGettersAndSetters,
4.44 - String[] methodsAndSignatures
4.45 - ) {
4.46 - applyImpl(propsGettersAndSetters, model.getClass(), model, model, methodsAndSignatures);
4.47 - return new Knockout(model);
4.48 - }
4.49 - public static <M> Knockout applyBindings(
4.50 - Class<M> modelClass, M model, String[] propsGettersAndSetters,
4.51 - String[] methodsAndSignatures
4.52 - ) {
4.53 - Knockout bindings = next;
4.54 - next = null;
4.55 - if (bindings == null) {
4.56 - bindings = new Knockout(null);
4.57 - }
4.58 - applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
4.59 - applyBindings(bindings);
4.60 - return bindings;
4.61 - }
4.62 -
4.63 - public void valueHasMutated(String prop) {
4.64 - valueHasMutated(model, prop);
4.65 - }
4.66 - @JavaScriptBody(args = { "self", "prop" }, body =
4.67 - "var p = self[prop]; if (p) p.valueHasMutated();"
4.68 - )
4.69 - public static void valueHasMutated(Object self, String prop) {
4.70 - }
4.71 -
4.72 -
4.73 - @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
4.74 - public static void triggerEvent(String id, String ev) {
4.75 - }
4.76 -
4.77 - @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
4.78 - "var bnd = {\n"
4.79 - + " 'read': function() {\n"
4.80 - + " var v = model[getter]();\n"
4.81 - + " if (array) v = v.koArray(); else if (v !== null) v = v.valueOf();\n"
4.82 - + " return v;\n"
4.83 - + " },\n"
4.84 - + " 'owner': bindings\n"
4.85 - + "};\n"
4.86 - + "if (setter != null) {\n"
4.87 - + " bnd['write'] = function(val) {\n"
4.88 - + " var v = val === null ? null : val.valueOf();"
4.89 - + " model[setter](v);\n"
4.90 - + " };\n"
4.91 - + "}\n"
4.92 - + "bindings[prop] = ko['computed'](bnd);"
4.93 - )
4.94 - static void bind(
4.95 - Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
4.96 - ) {
4.97 - }
4.98 -
4.99 - @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
4.100 - "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
4.101 - )
4.102 - static void expose(
4.103 - Object bindings, Object model, String prop, String sig
4.104 - ) {
4.105 - }
4.106 -
4.107 - @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
4.108 - static void applyBindings(Object bindings) {}
4.109 -
4.110 - private static void applyImpl(
4.111 - String[] propsGettersAndSetters,
4.112 - Class<?> modelClass,
4.113 - Object bindings,
4.114 - Object model,
4.115 - String[] methodsAndSignatures
4.116 - ) throws IllegalStateException, SecurityException {
4.117 - for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
4.118 - try {
4.119 - Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
4.120 - bind(bindings, model, propsGettersAndSetters[i],
4.121 - propsGettersAndSetters[i + 1],
4.122 - propsGettersAndSetters[i + 2],
4.123 - getter.getReturnType().isPrimitive(),
4.124 - List.class.isAssignableFrom(getter.getReturnType()));
4.125 - } catch (NoSuchMethodException ex) {
4.126 - throw new IllegalStateException(ex.getMessage());
4.127 - }
4.128 - }
4.129 - for (int i = 0; i < methodsAndSignatures.length; i += 2) {
4.130 - expose(
4.131 - bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
4.132 - }
4.133 - }
4.134 -}
5.1 --- a/ko/bck2brwsr/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js Mon Jan 06 13:45:57 2014 +0100
5.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
5.3 @@ -1,3614 +0,0 @@
5.4 -/*
5.5 - * HTML via Java(tm) Language Bindings
5.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5.7 - *
5.8 - * This program is free software: you can redistribute it and/or modify
5.9 - * it under the terms of the GNU General Public License as published by
5.10 - * the Free Software Foundation, version 2 of the License.
5.11 - *
5.12 - * This program is distributed in the hope that it will be useful,
5.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
5.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5.15 - * GNU General Public License for more details. apidesign.org
5.16 - * designates this particular file as subject to the
5.17 - * "Classpath" exception as provided by apidesign.org
5.18 - * in the License file that accompanied this code.
5.19 - *
5.20 - * You should have received a copy of the GNU General Public License
5.21 - * along with this program. Look for COPYING file in the top folder.
5.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
5.23 - */
5.24 -// Knockout JavaScript library v2.2.1
5.25 -// (c) Steven Sanderson - http://knockoutjs.com/
5.26 -// License: MIT (http://www.opensource.org/licenses/mit-license.php)
5.27 -
5.28 -(function(){
5.29 -var DEBUG=true;
5.30 -(function(window,document,navigator,jQuery,undefined){
5.31 -!function(factory) {
5.32 - // Support three module loading scenarios
5.33 - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
5.34 - // [1] CommonJS/Node.js
5.35 - var target = module['exports'] || exports; // module.exports is for Node.js
5.36 - factory(target);
5.37 - } else if (typeof define === 'function' && define['amd']) {
5.38 - // [2] AMD anonymous module
5.39 - define(['exports'], factory);
5.40 - } else {
5.41 - // [3] No module loader (plain <script> tag) - put directly in global namespace
5.42 - factory(window['ko'] = {});
5.43 - }
5.44 -}(function(koExports){
5.45 -// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
5.46 -// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
5.47 -var ko = typeof koExports !== 'undefined' ? koExports : {};
5.48 -// Google Closure Compiler helpers (used only to make the minified file smaller)
5.49 -ko.exportSymbol = function(koPath, object) {
5.50 - var tokens = koPath.split(".");
5.51 -
5.52 - // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
5.53 - // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
5.54 - var target = ko;
5.55 -
5.56 - for (var i = 0; i < tokens.length - 1; i++)
5.57 - target = target[tokens[i]];
5.58 - target[tokens[tokens.length - 1]] = object;
5.59 -};
5.60 -ko.exportProperty = function(owner, publicName, object) {
5.61 - owner[publicName] = object;
5.62 -};
5.63 -ko.version = "2.2.1";
5.64 -
5.65 -ko.exportSymbol('version', ko.version);
5.66 -ko.utils = new (function () {
5.67 - var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
5.68 -
5.69 - // 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)
5.70 - var knownEvents = {}, knownEventTypesByEventName = {};
5.71 - var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
5.72 - knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
5.73 - knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
5.74 - for (var eventType in knownEvents) {
5.75 - var knownEventsForType = knownEvents[eventType];
5.76 - if (knownEventsForType.length) {
5.77 - for (var i = 0, j = knownEventsForType.length; i < j; i++)
5.78 - knownEventTypesByEventName[knownEventsForType[i]] = eventType;
5.79 - }
5.80 - }
5.81 - var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
5.82 -
5.83 - // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
5.84 - // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
5.85 - // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
5.86 - // If there is a future need to detect specific versions of IE10+, we will amend this.
5.87 - var ieVersion = (function() {
5.88 - var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
5.89 -
5.90 - // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
5.91 - while (
5.92 - div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
5.93 - iElems[0]
5.94 - );
5.95 - return version > 4 ? version : undefined;
5.96 - }());
5.97 - var isIe6 = ieVersion === 6,
5.98 - isIe7 = ieVersion === 7;
5.99 -
5.100 - function isClickOnCheckableElement(element, eventType) {
5.101 - if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
5.102 - if (eventType.toLowerCase() != "click") return false;
5.103 - var inputType = element.type;
5.104 - return (inputType == "checkbox") || (inputType == "radio");
5.105 - }
5.106 -
5.107 - return {
5.108 - fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
5.109 -
5.110 - arrayForEach: function (array, action) {
5.111 - for (var i = 0, j = array.length; i < j; i++)
5.112 - action(array[i]);
5.113 - },
5.114 -
5.115 - arrayIndexOf: function (array, item) {
5.116 - if (typeof Array.prototype.indexOf == "function")
5.117 - return Array.prototype.indexOf.call(array, item);
5.118 - for (var i = 0, j = array.length; i < j; i++)
5.119 - if (array[i] === item)
5.120 - return i;
5.121 - return -1;
5.122 - },
5.123 -
5.124 - arrayFirst: function (array, predicate, predicateOwner) {
5.125 - for (var i = 0, j = array.length; i < j; i++)
5.126 - if (predicate.call(predicateOwner, array[i]))
5.127 - return array[i];
5.128 - return null;
5.129 - },
5.130 -
5.131 - arrayRemoveItem: function (array, itemToRemove) {
5.132 - var index = ko.utils.arrayIndexOf(array, itemToRemove);
5.133 - if (index >= 0)
5.134 - array.splice(index, 1);
5.135 - },
5.136 -
5.137 - arrayGetDistinctValues: function (array) {
5.138 - array = array || [];
5.139 - var result = [];
5.140 - for (var i = 0, j = array.length; i < j; i++) {
5.141 - if (ko.utils.arrayIndexOf(result, array[i]) < 0)
5.142 - result.push(array[i]);
5.143 - }
5.144 - return result;
5.145 - },
5.146 -
5.147 - arrayMap: function (array, mapping) {
5.148 - array = array || [];
5.149 - var result = [];
5.150 - for (var i = 0, j = array.length; i < j; i++)
5.151 - result.push(mapping(array[i]));
5.152 - return result;
5.153 - },
5.154 -
5.155 - arrayFilter: function (array, predicate) {
5.156 - array = array || [];
5.157 - var result = [];
5.158 - for (var i = 0, j = array.length; i < j; i++)
5.159 - if (predicate(array[i]))
5.160 - result.push(array[i]);
5.161 - return result;
5.162 - },
5.163 -
5.164 - arrayPushAll: function (array, valuesToPush) {
5.165 - if (valuesToPush instanceof Array)
5.166 - array.push.apply(array, valuesToPush);
5.167 - else
5.168 - for (var i = 0, j = valuesToPush.length; i < j; i++)
5.169 - array.push(valuesToPush[i]);
5.170 - return array;
5.171 - },
5.172 -
5.173 - extend: function (target, source) {
5.174 - if (source) {
5.175 - for(var prop in source) {
5.176 - if(source.hasOwnProperty(prop)) {
5.177 - target[prop] = source[prop];
5.178 - }
5.179 - }
5.180 - }
5.181 - return target;
5.182 - },
5.183 -
5.184 - emptyDomNode: function (domNode) {
5.185 - while (domNode.firstChild) {
5.186 - ko.removeNode(domNode.firstChild);
5.187 - }
5.188 - },
5.189 -
5.190 - moveCleanedNodesToContainerElement: function(nodes) {
5.191 - // Ensure it's a real array, as we're about to reparent the nodes and
5.192 - // we don't want the underlying collection to change while we're doing that.
5.193 - var nodesArray = ko.utils.makeArray(nodes);
5.194 -
5.195 - var container = document.createElement('div');
5.196 - for (var i = 0, j = nodesArray.length; i < j; i++) {
5.197 - container.appendChild(ko.cleanNode(nodesArray[i]));
5.198 - }
5.199 - return container;
5.200 - },
5.201 -
5.202 - cloneNodes: function (nodesArray, shouldCleanNodes) {
5.203 - for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
5.204 - var clonedNode = nodesArray[i].cloneNode(true);
5.205 - newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
5.206 - }
5.207 - return newNodesArray;
5.208 - },
5.209 -
5.210 - setDomNodeChildren: function (domNode, childNodes) {
5.211 - ko.utils.emptyDomNode(domNode);
5.212 - if (childNodes) {
5.213 - for (var i = 0, j = childNodes.length; i < j; i++)
5.214 - domNode.appendChild(childNodes[i]);
5.215 - }
5.216 - },
5.217 -
5.218 - replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
5.219 - var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
5.220 - if (nodesToReplaceArray.length > 0) {
5.221 - var insertionPoint = nodesToReplaceArray[0];
5.222 - var parent = insertionPoint.parentNode;
5.223 - for (var i = 0, j = newNodesArray.length; i < j; i++)
5.224 - parent.insertBefore(newNodesArray[i], insertionPoint);
5.225 - for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
5.226 - ko.removeNode(nodesToReplaceArray[i]);
5.227 - }
5.228 - }
5.229 - },
5.230 -
5.231 - setOptionNodeSelectionState: function (optionNode, isSelected) {
5.232 - // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
5.233 - if (ieVersion < 7)
5.234 - optionNode.setAttribute("selected", isSelected);
5.235 - else
5.236 - optionNode.selected = isSelected;
5.237 - },
5.238 -
5.239 - stringTrim: function (string) {
5.240 - return (string || "").replace(stringTrimRegex, "");
5.241 - },
5.242 -
5.243 - stringTokenize: function (string, delimiter) {
5.244 - var result = [];
5.245 - var tokens = (string || "").split(delimiter);
5.246 - for (var i = 0, j = tokens.length; i < j; i++) {
5.247 - var trimmed = ko.utils.stringTrim(tokens[i]);
5.248 - if (trimmed !== "")
5.249 - result.push(trimmed);
5.250 - }
5.251 - return result;
5.252 - },
5.253 -
5.254 - stringStartsWith: function (string, startsWith) {
5.255 - string = string || "";
5.256 - if (startsWith.length > string.length)
5.257 - return false;
5.258 - return string.substring(0, startsWith.length) === startsWith;
5.259 - },
5.260 -
5.261 - domNodeIsContainedBy: function (node, containedByNode) {
5.262 - if (containedByNode.compareDocumentPosition)
5.263 - return (containedByNode.compareDocumentPosition(node) & 16) == 16;
5.264 - while (node != null) {
5.265 - if (node == containedByNode)
5.266 - return true;
5.267 - node = node.parentNode;
5.268 - }
5.269 - return false;
5.270 - },
5.271 -
5.272 - domNodeIsAttachedToDocument: function (node) {
5.273 - return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
5.274 - },
5.275 -
5.276 - tagNameLower: function(element) {
5.277 - // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
5.278 - // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
5.279 - // we don't need to do the .toLowerCase() as it will always be lower case anyway.
5.280 - return element && element.tagName && element.tagName.toLowerCase();
5.281 - },
5.282 -
5.283 - registerEventHandler: function (element, eventType, handler) {
5.284 - var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
5.285 - if (!mustUseAttachEvent && typeof jQuery != "undefined") {
5.286 - if (isClickOnCheckableElement(element, eventType)) {
5.287 - // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
5.288 - // it toggles the element checked state *after* the click event handlers run, whereas native
5.289 - // click events toggle the checked state *before* the event handler.
5.290 - // Fix this by intecepting the handler and applying the correct checkedness before it runs.
5.291 - var originalHandler = handler;
5.292 - handler = function(event, eventData) {
5.293 - var jQuerySuppliedCheckedState = this.checked;
5.294 - if (eventData)
5.295 - this.checked = eventData.checkedStateBeforeEvent !== true;
5.296 - originalHandler.call(this, event);
5.297 - this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
5.298 - };
5.299 - }
5.300 - jQuery(element)['bind'](eventType, handler);
5.301 - } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
5.302 - element.addEventListener(eventType, handler, false);
5.303 - else if (typeof element.attachEvent != "undefined")
5.304 - element.attachEvent("on" + eventType, function (event) {
5.305 - handler.call(element, event);
5.306 - });
5.307 - else
5.308 - throw new Error("Browser doesn't support addEventListener or attachEvent");
5.309 - },
5.310 -
5.311 - triggerEvent: function (element, eventType) {
5.312 - if (!(element && element.nodeType))
5.313 - throw new Error("element must be a DOM node when calling triggerEvent");
5.314 -
5.315 - if (typeof jQuery != "undefined") {
5.316 - var eventData = [];
5.317 - if (isClickOnCheckableElement(element, eventType)) {
5.318 - // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
5.319 - eventData.push({ checkedStateBeforeEvent: element.checked });
5.320 - }
5.321 - jQuery(element)['trigger'](eventType, eventData);
5.322 - } else if (typeof document.createEvent == "function") {
5.323 - if (typeof element.dispatchEvent == "function") {
5.324 - var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
5.325 - var event = document.createEvent(eventCategory);
5.326 - event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
5.327 - element.dispatchEvent(event);
5.328 - }
5.329 - else
5.330 - throw new Error("The supplied element doesn't support dispatchEvent");
5.331 - } else if (typeof element.fireEvent != "undefined") {
5.332 - // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
5.333 - // so to make it consistent, we'll do it manually here
5.334 - if (isClickOnCheckableElement(element, eventType))
5.335 - element.checked = element.checked !== true;
5.336 - element.fireEvent("on" + eventType);
5.337 - }
5.338 - else
5.339 - throw new Error("Browser doesn't support triggering events");
5.340 - },
5.341 -
5.342 - unwrapObservable: function (value) {
5.343 - return ko.isObservable(value) ? value() : value;
5.344 - },
5.345 -
5.346 - peekObservable: function (value) {
5.347 - return ko.isObservable(value) ? value.peek() : value;
5.348 - },
5.349 -
5.350 - toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
5.351 - if (classNames) {
5.352 - var cssClassNameRegex = /[\w-]+/g,
5.353 - currentClassNames = node.className.match(cssClassNameRegex) || [];
5.354 - ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
5.355 - var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
5.356 - if (indexOfClass >= 0) {
5.357 - if (!shouldHaveClass)
5.358 - currentClassNames.splice(indexOfClass, 1);
5.359 - } else {
5.360 - if (shouldHaveClass)
5.361 - currentClassNames.push(className);
5.362 - }
5.363 - });
5.364 - node.className = currentClassNames.join(" ");
5.365 - }
5.366 - },
5.367 -
5.368 - setTextContent: function(element, textContent) {
5.369 - var value = ko.utils.unwrapObservable(textContent);
5.370 - if ((value === null) || (value === undefined))
5.371 - value = "";
5.372 -
5.373 - if (element.nodeType === 3) {
5.374 - element.data = value;
5.375 - } else {
5.376 - // We need there to be exactly one child: a text node.
5.377 - // If there are no children, more than one, or if it's not a text node,
5.378 - // we'll clear everything and create a single text node.
5.379 - var innerTextNode = ko.virtualElements.firstChild(element);
5.380 - if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
5.381 - ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
5.382 - } else {
5.383 - innerTextNode.data = value;
5.384 - }
5.385 -
5.386 - ko.utils.forceRefresh(element);
5.387 - }
5.388 - },
5.389 -
5.390 - setElementName: function(element, name) {
5.391 - element.name = name;
5.392 -
5.393 - // Workaround IE 6/7 issue
5.394 - // - https://github.com/SteveSanderson/knockout/issues/197
5.395 - // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
5.396 - if (ieVersion <= 7) {
5.397 - try {
5.398 - element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
5.399 - }
5.400 - catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
5.401 - }
5.402 - },
5.403 -
5.404 - forceRefresh: function(node) {
5.405 - // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
5.406 - if (ieVersion >= 9) {
5.407 - // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
5.408 - var elem = node.nodeType == 1 ? node : node.parentNode;
5.409 - if (elem.style)
5.410 - elem.style.zoom = elem.style.zoom;
5.411 - }
5.412 - },
5.413 -
5.414 - ensureSelectElementIsRenderedCorrectly: function(selectElement) {
5.415 - // 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.
5.416 - // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
5.417 - if (ieVersion >= 9) {
5.418 - var originalWidth = selectElement.style.width;
5.419 - selectElement.style.width = 0;
5.420 - selectElement.style.width = originalWidth;
5.421 - }
5.422 - },
5.423 -
5.424 - range: function (min, max) {
5.425 - min = ko.utils.unwrapObservable(min);
5.426 - max = ko.utils.unwrapObservable(max);
5.427 - var result = [];
5.428 - for (var i = min; i <= max; i++)
5.429 - result.push(i);
5.430 - return result;
5.431 - },
5.432 -
5.433 - makeArray: function(arrayLikeObject) {
5.434 - var result = [];
5.435 - for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
5.436 - result.push(arrayLikeObject[i]);
5.437 - };
5.438 - return result;
5.439 - },
5.440 -
5.441 - isIe6 : isIe6,
5.442 - isIe7 : isIe7,
5.443 - ieVersion : ieVersion,
5.444 -
5.445 - getFormFields: function(form, fieldName) {
5.446 - var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
5.447 - var isMatchingField = (typeof fieldName == 'string')
5.448 - ? function(field) { return field.name === fieldName }
5.449 - : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
5.450 - var matches = [];
5.451 - for (var i = fields.length - 1; i >= 0; i--) {
5.452 - if (isMatchingField(fields[i]))
5.453 - matches.push(fields[i]);
5.454 - };
5.455 - return matches;
5.456 - },
5.457 -
5.458 - parseJson: function (jsonString) {
5.459 - if (typeof jsonString == "string") {
5.460 - jsonString = ko.utils.stringTrim(jsonString);
5.461 - if (jsonString) {
5.462 - if (window.JSON && window.JSON.parse) // Use native parsing where available
5.463 - return window.JSON.parse(jsonString);
5.464 - return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
5.465 - }
5.466 - }
5.467 - return null;
5.468 - },
5.469 -
5.470 - stringifyJson: function (data, replacer, space) { // replacer and space are optional
5.471 - if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
5.472 - 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");
5.473 - return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
5.474 - },
5.475 -
5.476 - postJson: function (urlOrForm, data, options) {
5.477 - options = options || {};
5.478 - var params = options['params'] || {};
5.479 - var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
5.480 - var url = urlOrForm;
5.481 -
5.482 - // If we were given a form, use its 'action' URL and pick out any requested field values
5.483 - if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
5.484 - var originalForm = urlOrForm;
5.485 - url = originalForm.action;
5.486 - for (var i = includeFields.length - 1; i >= 0; i--) {
5.487 - var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
5.488 - for (var j = fields.length - 1; j >= 0; j--)
5.489 - params[fields[j].name] = fields[j].value;
5.490 - }
5.491 - }
5.492 -
5.493 - data = ko.utils.unwrapObservable(data);
5.494 - var form = document.createElement("form");
5.495 - form.style.display = "none";
5.496 - form.action = url;
5.497 - form.method = "post";
5.498 - for (var key in data) {
5.499 - var input = document.createElement("input");
5.500 - input.name = key;
5.501 - input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
5.502 - form.appendChild(input);
5.503 - }
5.504 - for (var key in params) {
5.505 - var input = document.createElement("input");
5.506 - input.name = key;
5.507 - input.value = params[key];
5.508 - form.appendChild(input);
5.509 - }
5.510 - document.body.appendChild(form);
5.511 - options['submitter'] ? options['submitter'](form) : form.submit();
5.512 - setTimeout(function () { form.parentNode.removeChild(form); }, 0);
5.513 - }
5.514 - }
5.515 -})();
5.516 -
5.517 -ko.exportSymbol('utils', ko.utils);
5.518 -ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
5.519 -ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
5.520 -ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
5.521 -ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
5.522 -ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
5.523 -ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
5.524 -ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
5.525 -ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
5.526 -ko.exportSymbol('utils.extend', ko.utils.extend);
5.527 -ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
5.528 -ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
5.529 -ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
5.530 -ko.exportSymbol('utils.postJson', ko.utils.postJson);
5.531 -ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
5.532 -ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
5.533 -ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
5.534 -ko.exportSymbol('utils.range', ko.utils.range);
5.535 -ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
5.536 -ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
5.537 -ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
5.538 -
5.539 -if (!Function.prototype['bind']) {
5.540 - // 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)
5.541 - // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
5.542 - Function.prototype['bind'] = function (object) {
5.543 - var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
5.544 - return function () {
5.545 - return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
5.546 - };
5.547 - };
5.548 -}
5.549 -
5.550 -ko.utils.domData = new (function () {
5.551 - var uniqueId = 0;
5.552 - var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
5.553 - var dataStore = {};
5.554 - return {
5.555 - get: function (node, key) {
5.556 - var allDataForNode = ko.utils.domData.getAll(node, false);
5.557 - return allDataForNode === undefined ? undefined : allDataForNode[key];
5.558 - },
5.559 - set: function (node, key, value) {
5.560 - if (value === undefined) {
5.561 - // Make sure we don't actually create a new domData key if we are actually deleting a value
5.562 - if (ko.utils.domData.getAll(node, false) === undefined)
5.563 - return;
5.564 - }
5.565 - var allDataForNode = ko.utils.domData.getAll(node, true);
5.566 - allDataForNode[key] = value;
5.567 - },
5.568 - getAll: function (node, createIfNotFound) {
5.569 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
5.570 - var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
5.571 - if (!hasExistingDataStore) {
5.572 - if (!createIfNotFound)
5.573 - return undefined;
5.574 - dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
5.575 - dataStore[dataStoreKey] = {};
5.576 - }
5.577 - return dataStore[dataStoreKey];
5.578 - },
5.579 - clear: function (node) {
5.580 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
5.581 - if (dataStoreKey) {
5.582 - delete dataStore[dataStoreKey];
5.583 - node[dataStoreKeyExpandoPropertyName] = null;
5.584 - return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
5.585 - }
5.586 - return false;
5.587 - }
5.588 - }
5.589 -})();
5.590 -
5.591 -ko.exportSymbol('utils.domData', ko.utils.domData);
5.592 -ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
5.593 -
5.594 -ko.utils.domNodeDisposal = new (function () {
5.595 - var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
5.596 - var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
5.597 - var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
5.598 -
5.599 - function getDisposeCallbacksCollection(node, createIfNotFound) {
5.600 - var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
5.601 - if ((allDisposeCallbacks === undefined) && createIfNotFound) {
5.602 - allDisposeCallbacks = [];
5.603 - ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
5.604 - }
5.605 - return allDisposeCallbacks;
5.606 - }
5.607 - function destroyCallbacksCollection(node) {
5.608 - ko.utils.domData.set(node, domDataKey, undefined);
5.609 - }
5.610 -
5.611 - function cleanSingleNode(node) {
5.612 - // Run all the dispose callbacks
5.613 - var callbacks = getDisposeCallbacksCollection(node, false);
5.614 - if (callbacks) {
5.615 - callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
5.616 - for (var i = 0; i < callbacks.length; i++)
5.617 - callbacks[i](node);
5.618 - }
5.619 -
5.620 - // Also erase the DOM data
5.621 - ko.utils.domData.clear(node);
5.622 -
5.623 - // Special support for jQuery here because it's so commonly used.
5.624 - // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
5.625 - // so notify it to tear down any resources associated with the node & descendants here.
5.626 - if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
5.627 - jQuery['cleanData']([node]);
5.628 -
5.629 - // Also clear any immediate-child comment nodes, as these wouldn't have been found by
5.630 - // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
5.631 - if (cleanableNodeTypesWithDescendants[node.nodeType])
5.632 - cleanImmediateCommentTypeChildren(node);
5.633 - }
5.634 -
5.635 - function cleanImmediateCommentTypeChildren(nodeWithChildren) {
5.636 - var child, nextChild = nodeWithChildren.firstChild;
5.637 - while (child = nextChild) {
5.638 - nextChild = child.nextSibling;
5.639 - if (child.nodeType === 8)
5.640 - cleanSingleNode(child);
5.641 - }
5.642 - }
5.643 -
5.644 - return {
5.645 - addDisposeCallback : function(node, callback) {
5.646 - if (typeof callback != "function")
5.647 - throw new Error("Callback must be a function");
5.648 - getDisposeCallbacksCollection(node, true).push(callback);
5.649 - },
5.650 -
5.651 - removeDisposeCallback : function(node, callback) {
5.652 - var callbacksCollection = getDisposeCallbacksCollection(node, false);
5.653 - if (callbacksCollection) {
5.654 - ko.utils.arrayRemoveItem(callbacksCollection, callback);
5.655 - if (callbacksCollection.length == 0)
5.656 - destroyCallbacksCollection(node);
5.657 - }
5.658 - },
5.659 -
5.660 - cleanNode : function(node) {
5.661 - // First clean this node, where applicable
5.662 - if (cleanableNodeTypes[node.nodeType]) {
5.663 - cleanSingleNode(node);
5.664 -
5.665 - // ... then its descendants, where applicable
5.666 - if (cleanableNodeTypesWithDescendants[node.nodeType]) {
5.667 - // Clone the descendants list in case it changes during iteration
5.668 - var descendants = [];
5.669 - ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
5.670 - for (var i = 0, j = descendants.length; i < j; i++)
5.671 - cleanSingleNode(descendants[i]);
5.672 - }
5.673 - }
5.674 - return node;
5.675 - },
5.676 -
5.677 - removeNode : function(node) {
5.678 - ko.cleanNode(node);
5.679 - if (node.parentNode)
5.680 - node.parentNode.removeChild(node);
5.681 - }
5.682 - }
5.683 -})();
5.684 -ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
5.685 -ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
5.686 -ko.exportSymbol('cleanNode', ko.cleanNode);
5.687 -ko.exportSymbol('removeNode', ko.removeNode);
5.688 -ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
5.689 -ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
5.690 -ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
5.691 -(function () {
5.692 - var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
5.693 -
5.694 - function simpleHtmlParse(html) {
5.695 - // Based on jQuery's "clean" function, but only accounting for table-related elements.
5.696 - // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
5.697 -
5.698 - // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
5.699 - // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
5.700 - // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
5.701 - // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
5.702 -
5.703 - // Trim whitespace, otherwise indexOf won't work as expected
5.704 - var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
5.705 -
5.706 - // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
5.707 - var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
5.708 - !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
5.709 - (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
5.710 - /* anything else */ [0, "", ""];
5.711 -
5.712 - // Go to html and back, then peel off extra wrappers
5.713 - // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
5.714 - var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
5.715 - if (typeof window['innerShiv'] == "function") {
5.716 - div.appendChild(window['innerShiv'](markup));
5.717 - } else {
5.718 - div.innerHTML = markup;
5.719 - }
5.720 -
5.721 - // Move to the right depth
5.722 - while (wrap[0]--)
5.723 - div = div.lastChild;
5.724 -
5.725 - return ko.utils.makeArray(div.lastChild.childNodes);
5.726 - }
5.727 -
5.728 - function jQueryHtmlParse(html) {
5.729 - // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
5.730 - if (jQuery['parseHTML']) {
5.731 - return jQuery['parseHTML'](html);
5.732 - } else {
5.733 - // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
5.734 - var elems = jQuery['clean']([html]);
5.735 -
5.736 - // 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.
5.737 - // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
5.738 - // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
5.739 - if (elems && elems[0]) {
5.740 - // Find the top-most parent element that's a direct child of a document fragment
5.741 - var elem = elems[0];
5.742 - while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
5.743 - elem = elem.parentNode;
5.744 - // ... then detach it
5.745 - if (elem.parentNode)
5.746 - elem.parentNode.removeChild(elem);
5.747 - }
5.748 -
5.749 - return elems;
5.750 - }
5.751 - }
5.752 -
5.753 - ko.utils.parseHtmlFragment = function(html) {
5.754 - return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
5.755 - : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
5.756 - };
5.757 -
5.758 - ko.utils.setHtml = function(node, html) {
5.759 - ko.utils.emptyDomNode(node);
5.760 -
5.761 - // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
5.762 - html = ko.utils.unwrapObservable(html);
5.763 -
5.764 - if ((html !== null) && (html !== undefined)) {
5.765 - if (typeof html != 'string')
5.766 - html = html.toString();
5.767 -
5.768 - // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
5.769 - // for example <tr> elements which are not normally allowed to exist on their own.
5.770 - // If you've referenced jQuery we'll use that rather than duplicating its code.
5.771 - if (typeof jQuery != 'undefined') {
5.772 - jQuery(node)['html'](html);
5.773 - } else {
5.774 - // ... otherwise, use KO's own parsing logic.
5.775 - var parsedNodes = ko.utils.parseHtmlFragment(html);
5.776 - for (var i = 0; i < parsedNodes.length; i++)
5.777 - node.appendChild(parsedNodes[i]);
5.778 - }
5.779 - }
5.780 - };
5.781 -})();
5.782 -
5.783 -ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
5.784 -ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
5.785 -
5.786 -ko.memoization = (function () {
5.787 - var memos = {};
5.788 -
5.789 - function randomMax8HexChars() {
5.790 - return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
5.791 - }
5.792 - function generateRandomId() {
5.793 - return randomMax8HexChars() + randomMax8HexChars();
5.794 - }
5.795 - function findMemoNodes(rootNode, appendToArray) {
5.796 - if (!rootNode)
5.797 - return;
5.798 - if (rootNode.nodeType == 8) {
5.799 - var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
5.800 - if (memoId != null)
5.801 - appendToArray.push({ domNode: rootNode, memoId: memoId });
5.802 - } else if (rootNode.nodeType == 1) {
5.803 - for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
5.804 - findMemoNodes(childNodes[i], appendToArray);
5.805 - }
5.806 - }
5.807 -
5.808 - return {
5.809 - memoize: function (callback) {
5.810 - if (typeof callback != "function")
5.811 - throw new Error("You can only pass a function to ko.memoization.memoize()");
5.812 - var memoId = generateRandomId();
5.813 - memos[memoId] = callback;
5.814 - return "<!--[ko_memo:" + memoId + "]-->";
5.815 - },
5.816 -
5.817 - unmemoize: function (memoId, callbackParams) {
5.818 - var callback = memos[memoId];
5.819 - if (callback === undefined)
5.820 - throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
5.821 - try {
5.822 - callback.apply(null, callbackParams || []);
5.823 - return true;
5.824 - }
5.825 - finally { delete memos[memoId]; }
5.826 - },
5.827 -
5.828 - unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
5.829 - var memos = [];
5.830 - findMemoNodes(domNode, memos);
5.831 - for (var i = 0, j = memos.length; i < j; i++) {
5.832 - var node = memos[i].domNode;
5.833 - var combinedParams = [node];
5.834 - if (extraCallbackParamsArray)
5.835 - ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
5.836 - ko.memoization.unmemoize(memos[i].memoId, combinedParams);
5.837 - node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
5.838 - if (node.parentNode)
5.839 - 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)
5.840 - }
5.841 - },
5.842 -
5.843 - parseMemoText: function (memoText) {
5.844 - var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
5.845 - return match ? match[1] : null;
5.846 - }
5.847 - };
5.848 -})();
5.849 -
5.850 -ko.exportSymbol('memoization', ko.memoization);
5.851 -ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
5.852 -ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
5.853 -ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
5.854 -ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
5.855 -ko.extenders = {
5.856 - 'throttle': function(target, timeout) {
5.857 - // Throttling means two things:
5.858 -
5.859 - // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
5.860 - // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
5.861 - target['throttleEvaluation'] = timeout;
5.862 -
5.863 - // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
5.864 - // so the target cannot change value synchronously or faster than a certain rate
5.865 - var writeTimeoutInstance = null;
5.866 - return ko.dependentObservable({
5.867 - 'read': target,
5.868 - 'write': function(value) {
5.869 - clearTimeout(writeTimeoutInstance);
5.870 - writeTimeoutInstance = setTimeout(function() {
5.871 - target(value);
5.872 - }, timeout);
5.873 - }
5.874 - });
5.875 - },
5.876 -
5.877 - 'notify': function(target, notifyWhen) {
5.878 - target["equalityComparer"] = notifyWhen == "always"
5.879 - ? function() { return false } // Treat all values as not equal
5.880 - : ko.observable["fn"]["equalityComparer"];
5.881 - return target;
5.882 - }
5.883 -};
5.884 -
5.885 -function applyExtenders(requestedExtenders) {
5.886 - var target = this;
5.887 - if (requestedExtenders) {
5.888 - for (var key in requestedExtenders) {
5.889 - var extenderHandler = ko.extenders[key];
5.890 - if (typeof extenderHandler == 'function') {
5.891 - target = extenderHandler(target, requestedExtenders[key]);
5.892 - }
5.893 - }
5.894 - }
5.895 - return target;
5.896 -}
5.897 -
5.898 -ko.exportSymbol('extenders', ko.extenders);
5.899 -
5.900 -ko.subscription = function (target, callback, disposeCallback) {
5.901 - this.target = target;
5.902 - this.callback = callback;
5.903 - this.disposeCallback = disposeCallback;
5.904 - ko.exportProperty(this, 'dispose', this.dispose);
5.905 -};
5.906 -ko.subscription.prototype.dispose = function () {
5.907 - this.isDisposed = true;
5.908 - this.disposeCallback();
5.909 -};
5.910 -
5.911 -ko.subscribable = function () {
5.912 - this._subscriptions = {};
5.913 -
5.914 - ko.utils.extend(this, ko.subscribable['fn']);
5.915 - ko.exportProperty(this, 'subscribe', this.subscribe);
5.916 - ko.exportProperty(this, 'extend', this.extend);
5.917 - ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
5.918 -}
5.919 -
5.920 -var defaultEvent = "change";
5.921 -
5.922 -ko.subscribable['fn'] = {
5.923 - subscribe: function (callback, callbackTarget, event) {
5.924 - event = event || defaultEvent;
5.925 - var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
5.926 -
5.927 - var subscription = new ko.subscription(this, boundCallback, function () {
5.928 - ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
5.929 - }.bind(this));
5.930 -
5.931 - if (!this._subscriptions[event])
5.932 - this._subscriptions[event] = [];
5.933 - this._subscriptions[event].push(subscription);
5.934 - return subscription;
5.935 - },
5.936 -
5.937 - "notifySubscribers": function (valueToNotify, event) {
5.938 - event = event || defaultEvent;
5.939 - if (this._subscriptions[event]) {
5.940 - ko.dependencyDetection.ignore(function() {
5.941 - ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
5.942 - // In case a subscription was disposed during the arrayForEach cycle, check
5.943 - // for isDisposed on each subscription before invoking its callback
5.944 - if (subscription && (subscription.isDisposed !== true))
5.945 - subscription.callback(valueToNotify);
5.946 - });
5.947 - }, this);
5.948 - }
5.949 - },
5.950 -
5.951 - getSubscriptionsCount: function () {
5.952 - var total = 0;
5.953 - for (var eventName in this._subscriptions) {
5.954 - if (this._subscriptions.hasOwnProperty(eventName))
5.955 - total += this._subscriptions[eventName].length;
5.956 - }
5.957 - return total;
5.958 - },
5.959 -
5.960 - extend: applyExtenders
5.961 -};
5.962 -
5.963 -
5.964 -ko.isSubscribable = function (instance) {
5.965 - return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
5.966 -};
5.967 -
5.968 -ko.exportSymbol('subscribable', ko.subscribable);
5.969 -ko.exportSymbol('isSubscribable', ko.isSubscribable);
5.970 -
5.971 -ko.dependencyDetection = (function () {
5.972 - var _frames = [];
5.973 -
5.974 - return {
5.975 - begin: function (callback) {
5.976 - _frames.push({ callback: callback, distinctDependencies:[] });
5.977 - },
5.978 -
5.979 - end: function () {
5.980 - _frames.pop();
5.981 - },
5.982 -
5.983 - registerDependency: function (subscribable) {
5.984 - if (!ko.isSubscribable(subscribable))
5.985 - throw new Error("Only subscribable things can act as dependencies");
5.986 - if (_frames.length > 0) {
5.987 - var topFrame = _frames[_frames.length - 1];
5.988 - if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
5.989 - return;
5.990 - topFrame.distinctDependencies.push(subscribable);
5.991 - topFrame.callback(subscribable);
5.992 - }
5.993 - },
5.994 -
5.995 - ignore: function(callback, callbackTarget, callbackArgs) {
5.996 - try {
5.997 - _frames.push(null);
5.998 - return callback.apply(callbackTarget, callbackArgs || []);
5.999 - } finally {
5.1000 - _frames.pop();
5.1001 - }
5.1002 - }
5.1003 - };
5.1004 -})();
5.1005 -var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
5.1006 -
5.1007 -ko.observable = function (initialValue) {
5.1008 - var _latestValue = initialValue;
5.1009 -
5.1010 - function observable() {
5.1011 - if (arguments.length > 0) {
5.1012 - // Write
5.1013 -
5.1014 - // Ignore writes if the value hasn't changed
5.1015 - if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
5.1016 - observable.valueWillMutate();
5.1017 - _latestValue = arguments[0];
5.1018 - if (DEBUG) observable._latestValue = _latestValue;
5.1019 - observable.valueHasMutated();
5.1020 - }
5.1021 - return this; // Permits chained assignments
5.1022 - }
5.1023 - else {
5.1024 - // Read
5.1025 - ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
5.1026 - return _latestValue;
5.1027 - }
5.1028 - }
5.1029 - if (DEBUG) observable._latestValue = _latestValue;
5.1030 - ko.subscribable.call(observable);
5.1031 - observable.peek = function() { return _latestValue };
5.1032 - observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
5.1033 - observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
5.1034 - ko.utils.extend(observable, ko.observable['fn']);
5.1035 -
5.1036 - ko.exportProperty(observable, 'peek', observable.peek);
5.1037 - ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
5.1038 - ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
5.1039 -
5.1040 - return observable;
5.1041 -}
5.1042 -
5.1043 -ko.observable['fn'] = {
5.1044 - "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
5.1045 - var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
5.1046 - return oldValueIsPrimitive ? (a === b) : false;
5.1047 - }
5.1048 -};
5.1049 -
5.1050 -var protoProperty = ko.observable.protoProperty = "__ko_proto__";
5.1051 -ko.observable['fn'][protoProperty] = ko.observable;
5.1052 -
5.1053 -ko.hasPrototype = function(instance, prototype) {
5.1054 - if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
5.1055 - if (instance[protoProperty] === prototype) return true;
5.1056 - return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
5.1057 -};
5.1058 -
5.1059 -ko.isObservable = function (instance) {
5.1060 - return ko.hasPrototype(instance, ko.observable);
5.1061 -}
5.1062 -ko.isWriteableObservable = function (instance) {
5.1063 - // Observable
5.1064 - if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
5.1065 - return true;
5.1066 - // Writeable dependent observable
5.1067 - if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
5.1068 - return true;
5.1069 - // Anything else
5.1070 - return false;
5.1071 -}
5.1072 -
5.1073 -
5.1074 -ko.exportSymbol('observable', ko.observable);
5.1075 -ko.exportSymbol('isObservable', ko.isObservable);
5.1076 -ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
5.1077 -ko.observableArray = function (initialValues) {
5.1078 - if (arguments.length == 0) {
5.1079 - // Zero-parameter constructor initializes to empty array
5.1080 - initialValues = [];
5.1081 - }
5.1082 - if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
5.1083 - throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
5.1084 -
5.1085 - var result = ko.observable(initialValues);
5.1086 - ko.utils.extend(result, ko.observableArray['fn']);
5.1087 - return result;
5.1088 -}
5.1089 -
5.1090 -ko.observableArray['fn'] = {
5.1091 - 'remove': function (valueOrPredicate) {
5.1092 - var underlyingArray = this.peek();
5.1093 - var removedValues = [];
5.1094 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
5.1095 - for (var i = 0; i < underlyingArray.length; i++) {
5.1096 - var value = underlyingArray[i];
5.1097 - if (predicate(value)) {
5.1098 - if (removedValues.length === 0) {
5.1099 - this.valueWillMutate();
5.1100 - }
5.1101 - removedValues.push(value);
5.1102 - underlyingArray.splice(i, 1);
5.1103 - i--;
5.1104 - }
5.1105 - }
5.1106 - if (removedValues.length) {
5.1107 - this.valueHasMutated();
5.1108 - }
5.1109 - return removedValues;
5.1110 - },
5.1111 -
5.1112 - 'removeAll': function (arrayOfValues) {
5.1113 - // If you passed zero args, we remove everything
5.1114 - if (arrayOfValues === undefined) {
5.1115 - var underlyingArray = this.peek();
5.1116 - var allValues = underlyingArray.slice(0);
5.1117 - this.valueWillMutate();
5.1118 - underlyingArray.splice(0, underlyingArray.length);
5.1119 - this.valueHasMutated();
5.1120 - return allValues;
5.1121 - }
5.1122 - // If you passed an arg, we interpret it as an array of entries to remove
5.1123 - if (!arrayOfValues)
5.1124 - return [];
5.1125 - return this['remove'](function (value) {
5.1126 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
5.1127 - });
5.1128 - },
5.1129 -
5.1130 - 'destroy': function (valueOrPredicate) {
5.1131 - var underlyingArray = this.peek();
5.1132 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
5.1133 - this.valueWillMutate();
5.1134 - for (var i = underlyingArray.length - 1; i >= 0; i--) {
5.1135 - var value = underlyingArray[i];
5.1136 - if (predicate(value))
5.1137 - underlyingArray[i]["_destroy"] = true;
5.1138 - }
5.1139 - this.valueHasMutated();
5.1140 - },
5.1141 -
5.1142 - 'destroyAll': function (arrayOfValues) {
5.1143 - // If you passed zero args, we destroy everything
5.1144 - if (arrayOfValues === undefined)
5.1145 - return this['destroy'](function() { return true });
5.1146 -
5.1147 - // If you passed an arg, we interpret it as an array of entries to destroy
5.1148 - if (!arrayOfValues)
5.1149 - return [];
5.1150 - return this['destroy'](function (value) {
5.1151 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
5.1152 - });
5.1153 - },
5.1154 -
5.1155 - 'indexOf': function (item) {
5.1156 - var underlyingArray = this();
5.1157 - return ko.utils.arrayIndexOf(underlyingArray, item);
5.1158 - },
5.1159 -
5.1160 - 'replace': function(oldItem, newItem) {
5.1161 - var index = this['indexOf'](oldItem);
5.1162 - if (index >= 0) {
5.1163 - this.valueWillMutate();
5.1164 - this.peek()[index] = newItem;
5.1165 - this.valueHasMutated();
5.1166 - }
5.1167 - }
5.1168 -}
5.1169 -
5.1170 -// Populate ko.observableArray.fn with read/write functions from native arrays
5.1171 -// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
5.1172 -// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
5.1173 -ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
5.1174 - ko.observableArray['fn'][methodName] = function () {
5.1175 - // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
5.1176 - // (for consistency with mutating regular observables)
5.1177 - var underlyingArray = this.peek();
5.1178 - this.valueWillMutate();
5.1179 - var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
5.1180 - this.valueHasMutated();
5.1181 - return methodCallResult;
5.1182 - };
5.1183 -});
5.1184 -
5.1185 -// Populate ko.observableArray.fn with read-only functions from native arrays
5.1186 -ko.utils.arrayForEach(["slice"], function (methodName) {
5.1187 - ko.observableArray['fn'][methodName] = function () {
5.1188 - var underlyingArray = this();
5.1189 - return underlyingArray[methodName].apply(underlyingArray, arguments);
5.1190 - };
5.1191 -});
5.1192 -
5.1193 -ko.exportSymbol('observableArray', ko.observableArray);
5.1194 -ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
5.1195 - var _latestValue,
5.1196 - _hasBeenEvaluated = false,
5.1197 - _isBeingEvaluated = false,
5.1198 - readFunction = evaluatorFunctionOrOptions;
5.1199 -
5.1200 - if (readFunction && typeof readFunction == "object") {
5.1201 - // Single-parameter syntax - everything is on this "options" param
5.1202 - options = readFunction;
5.1203 - readFunction = options["read"];
5.1204 - } else {
5.1205 - // Multi-parameter syntax - construct the options according to the params passed
5.1206 - options = options || {};
5.1207 - if (!readFunction)
5.1208 - readFunction = options["read"];
5.1209 - }
5.1210 - if (typeof readFunction != "function")
5.1211 - throw new Error("Pass a function that returns the value of the ko.computed");
5.1212 -
5.1213 - function addSubscriptionToDependency(subscribable) {
5.1214 - _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
5.1215 - }
5.1216 -
5.1217 - function disposeAllSubscriptionsToDependencies() {
5.1218 - ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
5.1219 - subscription.dispose();
5.1220 - });
5.1221 - _subscriptionsToDependencies = [];
5.1222 - }
5.1223 -
5.1224 - function evaluatePossiblyAsync() {
5.1225 - var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
5.1226 - if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
5.1227 - clearTimeout(evaluationTimeoutInstance);
5.1228 - evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
5.1229 - } else
5.1230 - evaluateImmediate();
5.1231 - }
5.1232 -
5.1233 - function evaluateImmediate() {
5.1234 - if (_isBeingEvaluated) {
5.1235 - // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
5.1236 - // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
5.1237 - // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
5.1238 - // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
5.1239 - return;
5.1240 - }
5.1241 -
5.1242 - // Don't dispose on first evaluation, because the "disposeWhen" callback might
5.1243 - // e.g., dispose when the associated DOM element isn't in the doc, and it's not
5.1244 - // going to be in the doc until *after* the first evaluation
5.1245 - if (_hasBeenEvaluated && disposeWhen()) {
5.1246 - dispose();
5.1247 - return;
5.1248 - }
5.1249 -
5.1250 - _isBeingEvaluated = true;
5.1251 - try {
5.1252 - // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
5.1253 - // Then, during evaluation, we cross off any that are in fact still being used.
5.1254 - var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
5.1255 -
5.1256 - ko.dependencyDetection.begin(function(subscribable) {
5.1257 - var inOld;
5.1258 - if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
5.1259 - disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
5.1260 - else
5.1261 - addSubscriptionToDependency(subscribable); // Brand new subscription - add it
5.1262 - });
5.1263 -
5.1264 - var newValue = readFunction.call(evaluatorFunctionTarget);
5.1265 -
5.1266 - // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
5.1267 - for (var i = disposalCandidates.length - 1; i >= 0; i--) {
5.1268 - if (disposalCandidates[i])
5.1269 - _subscriptionsToDependencies.splice(i, 1)[0].dispose();
5.1270 - }
5.1271 - _hasBeenEvaluated = true;
5.1272 -
5.1273 - dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
5.1274 - _latestValue = newValue;
5.1275 - if (DEBUG) dependentObservable._latestValue = _latestValue;
5.1276 - } finally {
5.1277 - ko.dependencyDetection.end();
5.1278 - }
5.1279 -
5.1280 - dependentObservable["notifySubscribers"](_latestValue);
5.1281 - _isBeingEvaluated = false;
5.1282 - if (!_subscriptionsToDependencies.length)
5.1283 - dispose();
5.1284 - }
5.1285 -
5.1286 - function dependentObservable() {
5.1287 - if (arguments.length > 0) {
5.1288 - if (typeof writeFunction === "function") {
5.1289 - // Writing a value
5.1290 - writeFunction.apply(evaluatorFunctionTarget, arguments);
5.1291 - } else {
5.1292 - 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.");
5.1293 - }
5.1294 - return this; // Permits chained assignments
5.1295 - } else {
5.1296 - // Reading the value
5.1297 - if (!_hasBeenEvaluated)
5.1298 - evaluateImmediate();
5.1299 - ko.dependencyDetection.registerDependency(dependentObservable);
5.1300 - return _latestValue;
5.1301 - }
5.1302 - }
5.1303 -
5.1304 - function peek() {
5.1305 - if (!_hasBeenEvaluated)
5.1306 - evaluateImmediate();
5.1307 - return _latestValue;
5.1308 - }
5.1309 -
5.1310 - function isActive() {
5.1311 - return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
5.1312 - }
5.1313 -
5.1314 - // By here, "options" is always non-null
5.1315 - var writeFunction = options["write"],
5.1316 - disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
5.1317 - disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
5.1318 - dispose = disposeAllSubscriptionsToDependencies,
5.1319 - _subscriptionsToDependencies = [],
5.1320 - evaluationTimeoutInstance = null;
5.1321 -
5.1322 - if (!evaluatorFunctionTarget)
5.1323 - evaluatorFunctionTarget = options["owner"];
5.1324 -
5.1325 - dependentObservable.peek = peek;
5.1326 - dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
5.1327 - dependentObservable.hasWriteFunction = typeof options["write"] === "function";
5.1328 - dependentObservable.dispose = function () { dispose(); };
5.1329 - dependentObservable.isActive = isActive;
5.1330 - dependentObservable.valueHasMutated = function() {
5.1331 - _hasBeenEvaluated = false;
5.1332 - evaluateImmediate();
5.1333 - };
5.1334 -
5.1335 - ko.subscribable.call(dependentObservable);
5.1336 - ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
5.1337 -
5.1338 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
5.1339 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
5.1340 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
5.1341 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
5.1342 -
5.1343 - // Evaluate, unless deferEvaluation is true
5.1344 - if (options['deferEvaluation'] !== true)
5.1345 - evaluateImmediate();
5.1346 -
5.1347 - // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
5.1348 - // But skip if isActive is false (there will never be any dependencies to dispose).
5.1349 - // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
5.1350 - // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
5.1351 - if (disposeWhenNodeIsRemoved && isActive()) {
5.1352 - dispose = function() {
5.1353 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
5.1354 - disposeAllSubscriptionsToDependencies();
5.1355 - };
5.1356 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
5.1357 - var existingDisposeWhenFunction = disposeWhen;
5.1358 - disposeWhen = function () {
5.1359 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
5.1360 - }
5.1361 - }
5.1362 -
5.1363 - return dependentObservable;
5.1364 -};
5.1365 -
5.1366 -ko.isComputed = function(instance) {
5.1367 - return ko.hasPrototype(instance, ko.dependentObservable);
5.1368 -};
5.1369 -
5.1370 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
5.1371 -ko.dependentObservable[protoProp] = ko.observable;
5.1372 -
5.1373 -ko.dependentObservable['fn'] = {};
5.1374 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
5.1375 -
5.1376 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
5.1377 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
5.1378 -ko.exportSymbol('isComputed', ko.isComputed);
5.1379 -
5.1380 -(function() {
5.1381 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
5.1382 -
5.1383 - ko.toJS = function(rootObject) {
5.1384 - if (arguments.length == 0)
5.1385 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
5.1386 -
5.1387 - // We just unwrap everything at every level in the object graph
5.1388 - return mapJsObjectGraph(rootObject, function(valueToMap) {
5.1389 - // Loop because an observable's value might in turn be another observable wrapper
5.1390 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
5.1391 - valueToMap = valueToMap();
5.1392 - return valueToMap;
5.1393 - });
5.1394 - };
5.1395 -
5.1396 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
5.1397 - var plainJavaScriptObject = ko.toJS(rootObject);
5.1398 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
5.1399 - };
5.1400 -
5.1401 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
5.1402 - visitedObjects = visitedObjects || new objectLookup();
5.1403 -
5.1404 - rootObject = mapInputCallback(rootObject);
5.1405 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
5.1406 - if (!canHaveProperties)
5.1407 - return rootObject;
5.1408 -
5.1409 - var outputProperties = rootObject instanceof Array ? [] : {};
5.1410 - visitedObjects.save(rootObject, outputProperties);
5.1411 -
5.1412 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
5.1413 - var propertyValue = mapInputCallback(rootObject[indexer]);
5.1414 -
5.1415 - switch (typeof propertyValue) {
5.1416 - case "boolean":
5.1417 - case "number":
5.1418 - case "string":
5.1419 - case "function":
5.1420 - outputProperties[indexer] = propertyValue;
5.1421 - break;
5.1422 - case "object":
5.1423 - case "undefined":
5.1424 - var previouslyMappedValue = visitedObjects.get(propertyValue);
5.1425 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
5.1426 - ? previouslyMappedValue
5.1427 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
5.1428 - break;
5.1429 - }
5.1430 - });
5.1431 -
5.1432 - return outputProperties;
5.1433 - }
5.1434 -
5.1435 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
5.1436 - if (rootObject instanceof Array) {
5.1437 - for (var i = 0; i < rootObject.length; i++)
5.1438 - visitorCallback(i);
5.1439 -
5.1440 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
5.1441 - if (typeof rootObject['toJSON'] == 'function')
5.1442 - visitorCallback('toJSON');
5.1443 - } else {
5.1444 - for (var propertyName in rootObject)
5.1445 - visitorCallback(propertyName);
5.1446 - }
5.1447 - };
5.1448 -
5.1449 - function objectLookup() {
5.1450 - var keys = [];
5.1451 - var values = [];
5.1452 - this.save = function(key, value) {
5.1453 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
5.1454 - if (existingIndex >= 0)
5.1455 - values[existingIndex] = value;
5.1456 - else {
5.1457 - keys.push(key);
5.1458 - values.push(value);
5.1459 - }
5.1460 - };
5.1461 - this.get = function(key) {
5.1462 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
5.1463 - return (existingIndex >= 0) ? values[existingIndex] : undefined;
5.1464 - };
5.1465 - };
5.1466 -})();
5.1467 -
5.1468 -ko.exportSymbol('toJS', ko.toJS);
5.1469 -ko.exportSymbol('toJSON', ko.toJSON);
5.1470 -(function () {
5.1471 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
5.1472 -
5.1473 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
5.1474 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
5.1475 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
5.1476 - ko.selectExtensions = {
5.1477 - readValue : function(element) {
5.1478 - switch (ko.utils.tagNameLower(element)) {
5.1479 - case 'option':
5.1480 - if (element[hasDomDataExpandoProperty] === true)
5.1481 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
5.1482 - return ko.utils.ieVersion <= 7
5.1483 - ? (element.getAttributeNode('value').specified ? element.value : element.text)
5.1484 - : element.value;
5.1485 - case 'select':
5.1486 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
5.1487 - default:
5.1488 - return element.value;
5.1489 - }
5.1490 - },
5.1491 -
5.1492 - writeValue: function(element, value) {
5.1493 - switch (ko.utils.tagNameLower(element)) {
5.1494 - case 'option':
5.1495 - switch(typeof value) {
5.1496 - case "string":
5.1497 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
5.1498 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
5.1499 - delete element[hasDomDataExpandoProperty];
5.1500 - }
5.1501 - element.value = value;
5.1502 - break;
5.1503 - default:
5.1504 - // Store arbitrary object using DomData
5.1505 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
5.1506 - element[hasDomDataExpandoProperty] = true;
5.1507 -
5.1508 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
5.1509 - element.value = typeof value === "number" ? value : "";
5.1510 - break;
5.1511 - }
5.1512 - break;
5.1513 - case 'select':
5.1514 - for (var i = element.options.length - 1; i >= 0; i--) {
5.1515 - if (ko.selectExtensions.readValue(element.options[i]) == value) {
5.1516 - element.selectedIndex = i;
5.1517 - break;
5.1518 - }
5.1519 - }
5.1520 - break;
5.1521 - default:
5.1522 - if ((value === null) || (value === undefined))
5.1523 - value = "";
5.1524 - element.value = value;
5.1525 - break;
5.1526 - }
5.1527 - }
5.1528 - };
5.1529 -})();
5.1530 -
5.1531 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
5.1532 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
5.1533 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
5.1534 -ko.expressionRewriting = (function () {
5.1535 - var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
5.1536 - var javaScriptReservedWords = ["true", "false"];
5.1537 -
5.1538 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
5.1539 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
5.1540 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
5.1541 -
5.1542 - function restoreTokens(string, tokens) {
5.1543 - var prevValue = null;
5.1544 - while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
5.1545 - prevValue = string;
5.1546 - string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
5.1547 - return tokens[tokenIndex];
5.1548 - });
5.1549 - }
5.1550 - return string;
5.1551 - }
5.1552 -
5.1553 - function getWriteableValue(expression) {
5.1554 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
5.1555 - return false;
5.1556 - var match = expression.match(javaScriptAssignmentTarget);
5.1557 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
5.1558 - }
5.1559 -
5.1560 - function ensureQuoted(key) {
5.1561 - var trimmedKey = ko.utils.stringTrim(key);
5.1562 - switch (trimmedKey.length && trimmedKey.charAt(0)) {
5.1563 - case "'":
5.1564 - case '"':
5.1565 - return key;
5.1566 - default:
5.1567 - return "'" + trimmedKey + "'";
5.1568 - }
5.1569 - }
5.1570 -
5.1571 - return {
5.1572 - bindingRewriteValidators: [],
5.1573 -
5.1574 - parseObjectLiteral: function(objectLiteralString) {
5.1575 - // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
5.1576 - // that is sufficient just to split an object literal string into a set of top-level key-value pairs
5.1577 -
5.1578 - var str = ko.utils.stringTrim(objectLiteralString);
5.1579 - if (str.length < 3)
5.1580 - return [];
5.1581 - if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
5.1582 - str = str.substring(1, str.length - 1);
5.1583 -
5.1584 - // Pull out any string literals and regex literals
5.1585 - var tokens = [];
5.1586 - var tokenStart = null, tokenEndChar;
5.1587 - for (var position = 0; position < str.length; position++) {
5.1588 - var c = str.charAt(position);
5.1589 - if (tokenStart === null) {
5.1590 - switch (c) {
5.1591 - case '"':
5.1592 - case "'":
5.1593 - case "/":
5.1594 - tokenStart = position;
5.1595 - tokenEndChar = c;
5.1596 - break;
5.1597 - }
5.1598 - } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
5.1599 - var token = str.substring(tokenStart, position + 1);
5.1600 - tokens.push(token);
5.1601 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
5.1602 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
5.1603 - position -= (token.length - replacement.length);
5.1604 - tokenStart = null;
5.1605 - }
5.1606 - }
5.1607 -
5.1608 - // Next pull out balanced paren, brace, and bracket blocks
5.1609 - tokenStart = null;
5.1610 - tokenEndChar = null;
5.1611 - var tokenDepth = 0, tokenStartChar = null;
5.1612 - for (var position = 0; position < str.length; position++) {
5.1613 - var c = str.charAt(position);
5.1614 - if (tokenStart === null) {
5.1615 - switch (c) {
5.1616 - case "{": tokenStart = position; tokenStartChar = c;
5.1617 - tokenEndChar = "}";
5.1618 - break;
5.1619 - case "(": tokenStart = position; tokenStartChar = c;
5.1620 - tokenEndChar = ")";
5.1621 - break;
5.1622 - case "[": tokenStart = position; tokenStartChar = c;
5.1623 - tokenEndChar = "]";
5.1624 - break;
5.1625 - }
5.1626 - }
5.1627 -
5.1628 - if (c === tokenStartChar)
5.1629 - tokenDepth++;
5.1630 - else if (c === tokenEndChar) {
5.1631 - tokenDepth--;
5.1632 - if (tokenDepth === 0) {
5.1633 - var token = str.substring(tokenStart, position + 1);
5.1634 - tokens.push(token);
5.1635 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
5.1636 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
5.1637 - position -= (token.length - replacement.length);
5.1638 - tokenStart = null;
5.1639 - }
5.1640 - }
5.1641 - }
5.1642 -
5.1643 - // Now we can safely split on commas to get the key/value pairs
5.1644 - var result = [];
5.1645 - var keyValuePairs = str.split(",");
5.1646 - for (var i = 0, j = keyValuePairs.length; i < j; i++) {
5.1647 - var pair = keyValuePairs[i];
5.1648 - var colonPos = pair.indexOf(":");
5.1649 - if ((colonPos > 0) && (colonPos < pair.length - 1)) {
5.1650 - var key = pair.substring(0, colonPos);
5.1651 - var value = pair.substring(colonPos + 1);
5.1652 - result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
5.1653 - } else {
5.1654 - result.push({ 'unknown': restoreTokens(pair, tokens) });
5.1655 - }
5.1656 - }
5.1657 - return result;
5.1658 - },
5.1659 -
5.1660 - preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
5.1661 - var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
5.1662 - ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
5.1663 - : objectLiteralStringOrKeyValueArray;
5.1664 - var resultStrings = [], propertyAccessorResultStrings = [];
5.1665 -
5.1666 - var keyValueEntry;
5.1667 - for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
5.1668 - if (resultStrings.length > 0)
5.1669 - resultStrings.push(",");
5.1670 -
5.1671 - if (keyValueEntry['key']) {
5.1672 - var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
5.1673 - resultStrings.push(quotedKey);
5.1674 - resultStrings.push(":");
5.1675 - resultStrings.push(val);
5.1676 -
5.1677 - if (val = getWriteableValue(ko.utils.stringTrim(val))) {
5.1678 - if (propertyAccessorResultStrings.length > 0)
5.1679 - propertyAccessorResultStrings.push(", ");
5.1680 - propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
5.1681 - }
5.1682 - } else if (keyValueEntry['unknown']) {
5.1683 - resultStrings.push(keyValueEntry['unknown']);
5.1684 - }
5.1685 - }
5.1686 -
5.1687 - var combinedResult = resultStrings.join("");
5.1688 - if (propertyAccessorResultStrings.length > 0) {
5.1689 - var allPropertyAccessors = propertyAccessorResultStrings.join("");
5.1690 - combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
5.1691 - }
5.1692 -
5.1693 - return combinedResult;
5.1694 - },
5.1695 -
5.1696 - keyValueArrayContainsKey: function(keyValueArray, key) {
5.1697 - for (var i = 0; i < keyValueArray.length; i++)
5.1698 - if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
5.1699 - return true;
5.1700 - return false;
5.1701 - },
5.1702 -
5.1703 - // Internal, private KO utility for updating model properties from within bindings
5.1704 - // property: If the property being updated is (or might be) an observable, pass it here
5.1705 - // If it turns out to be a writable observable, it will be written to directly
5.1706 - // allBindingsAccessor: All bindings in the current execution context.
5.1707 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
5.1708 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
5.1709 - // value: The value to be written
5.1710 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
5.1711 - // it is !== existing value on that writable observable
5.1712 - writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
5.1713 - if (!property || !ko.isWriteableObservable(property)) {
5.1714 - var propWriters = allBindingsAccessor()['_ko_property_writers'];
5.1715 - if (propWriters && propWriters[key])
5.1716 - propWriters[key](value);
5.1717 - } else if (!checkIfDifferent || property.peek() !== value) {
5.1718 - property(value);
5.1719 - }
5.1720 - }
5.1721 - };
5.1722 -})();
5.1723 -
5.1724 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
5.1725 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
5.1726 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
5.1727 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
5.1728 -
5.1729 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
5.1730 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
5.1731 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
5.1732 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
5.1733 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
5.1734 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
5.1735 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
5.1736 - // of that virtual hierarchy
5.1737 - //
5.1738 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
5.1739 - // without having to scatter special cases all over the binding and templating code.
5.1740 -
5.1741 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
5.1742 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
5.1743 - // So, use node.text where available, and node.nodeValue elsewhere
5.1744 - var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
5.1745 -
5.1746 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
5.1747 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
5.1748 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
5.1749 -
5.1750 - function isStartComment(node) {
5.1751 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
5.1752 - }
5.1753 -
5.1754 - function isEndComment(node) {
5.1755 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
5.1756 - }
5.1757 -
5.1758 - function getVirtualChildren(startComment, allowUnbalanced) {
5.1759 - var currentNode = startComment;
5.1760 - var depth = 1;
5.1761 - var children = [];
5.1762 - while (currentNode = currentNode.nextSibling) {
5.1763 - if (isEndComment(currentNode)) {
5.1764 - depth--;
5.1765 - if (depth === 0)
5.1766 - return children;
5.1767 - }
5.1768 -
5.1769 - children.push(currentNode);
5.1770 -
5.1771 - if (isStartComment(currentNode))
5.1772 - depth++;
5.1773 - }
5.1774 - if (!allowUnbalanced)
5.1775 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
5.1776 - return null;
5.1777 - }
5.1778 -
5.1779 - function getMatchingEndComment(startComment, allowUnbalanced) {
5.1780 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
5.1781 - if (allVirtualChildren) {
5.1782 - if (allVirtualChildren.length > 0)
5.1783 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
5.1784 - return startComment.nextSibling;
5.1785 - } else
5.1786 - return null; // Must have no matching end comment, and allowUnbalanced is true
5.1787 - }
5.1788 -
5.1789 - function getUnbalancedChildTags(node) {
5.1790 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
5.1791 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
5.1792 - var childNode = node.firstChild, captureRemaining = null;
5.1793 - if (childNode) {
5.1794 - do {
5.1795 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
5.1796 - captureRemaining.push(childNode);
5.1797 - else if (isStartComment(childNode)) {
5.1798 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
5.1799 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
5.1800 - childNode = matchingEndComment;
5.1801 - else
5.1802 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
5.1803 - } else if (isEndComment(childNode)) {
5.1804 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
5.1805 - }
5.1806 - } while (childNode = childNode.nextSibling);
5.1807 - }
5.1808 - return captureRemaining;
5.1809 - }
5.1810 -
5.1811 - ko.virtualElements = {
5.1812 - allowedBindings: {},
5.1813 -
5.1814 - childNodes: function(node) {
5.1815 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
5.1816 - },
5.1817 -
5.1818 - emptyNode: function(node) {
5.1819 - if (!isStartComment(node))
5.1820 - ko.utils.emptyDomNode(node);
5.1821 - else {
5.1822 - var virtualChildren = ko.virtualElements.childNodes(node);
5.1823 - for (var i = 0, j = virtualChildren.length; i < j; i++)
5.1824 - ko.removeNode(virtualChildren[i]);
5.1825 - }
5.1826 - },
5.1827 -
5.1828 - setDomNodeChildren: function(node, childNodes) {
5.1829 - if (!isStartComment(node))
5.1830 - ko.utils.setDomNodeChildren(node, childNodes);
5.1831 - else {
5.1832 - ko.virtualElements.emptyNode(node);
5.1833 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
5.1834 - for (var i = 0, j = childNodes.length; i < j; i++)
5.1835 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
5.1836 - }
5.1837 - },
5.1838 -
5.1839 - prepend: function(containerNode, nodeToPrepend) {
5.1840 - if (!isStartComment(containerNode)) {
5.1841 - if (containerNode.firstChild)
5.1842 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
5.1843 - else
5.1844 - containerNode.appendChild(nodeToPrepend);
5.1845 - } else {
5.1846 - // Start comments must always have a parent and at least one following sibling (the end comment)
5.1847 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
5.1848 - }
5.1849 - },
5.1850 -
5.1851 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
5.1852 - if (!insertAfterNode) {
5.1853 - ko.virtualElements.prepend(containerNode, nodeToInsert);
5.1854 - } else if (!isStartComment(containerNode)) {
5.1855 - // Insert after insertion point
5.1856 - if (insertAfterNode.nextSibling)
5.1857 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
5.1858 - else
5.1859 - containerNode.appendChild(nodeToInsert);
5.1860 - } else {
5.1861 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
5.1862 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
5.1863 - }
5.1864 - },
5.1865 -
5.1866 - firstChild: function(node) {
5.1867 - if (!isStartComment(node))
5.1868 - return node.firstChild;
5.1869 - if (!node.nextSibling || isEndComment(node.nextSibling))
5.1870 - return null;
5.1871 - return node.nextSibling;
5.1872 - },
5.1873 -
5.1874 - nextSibling: function(node) {
5.1875 - if (isStartComment(node))
5.1876 - node = getMatchingEndComment(node);
5.1877 - if (node.nextSibling && isEndComment(node.nextSibling))
5.1878 - return null;
5.1879 - return node.nextSibling;
5.1880 - },
5.1881 -
5.1882 - virtualNodeBindingValue: function(node) {
5.1883 - var regexMatch = isStartComment(node);
5.1884 - return regexMatch ? regexMatch[1] : null;
5.1885 - },
5.1886 -
5.1887 - normaliseVirtualElementDomStructure: function(elementVerified) {
5.1888 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
5.1889 - // (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
5.1890 - // that are direct descendants of <ul> into the preceding <li>)
5.1891 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
5.1892 - return;
5.1893 -
5.1894 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
5.1895 - // must be intended to appear *after* that child, so move them there.
5.1896 - var childNode = elementVerified.firstChild;
5.1897 - if (childNode) {
5.1898 - do {
5.1899 - if (childNode.nodeType === 1) {
5.1900 - var unbalancedTags = getUnbalancedChildTags(childNode);
5.1901 - if (unbalancedTags) {
5.1902 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
5.1903 - var nodeToInsertBefore = childNode.nextSibling;
5.1904 - for (var i = 0; i < unbalancedTags.length; i++) {
5.1905 - if (nodeToInsertBefore)
5.1906 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
5.1907 - else
5.1908 - elementVerified.appendChild(unbalancedTags[i]);
5.1909 - }
5.1910 - }
5.1911 - }
5.1912 - } while (childNode = childNode.nextSibling);
5.1913 - }
5.1914 - }
5.1915 - };
5.1916 -})();
5.1917 -ko.exportSymbol('virtualElements', ko.virtualElements);
5.1918 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
5.1919 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
5.1920 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
5.1921 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
5.1922 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
5.1923 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
5.1924 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
5.1925 -(function() {
5.1926 - var defaultBindingAttributeName = "data-bind";
5.1927 -
5.1928 - ko.bindingProvider = function() {
5.1929 - this.bindingCache = {};
5.1930 - };
5.1931 -
5.1932 - ko.utils.extend(ko.bindingProvider.prototype, {
5.1933 - 'nodeHasBindings': function(node) {
5.1934 - switch (node.nodeType) {
5.1935 - case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
5.1936 - case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
5.1937 - default: return false;
5.1938 - }
5.1939 - },
5.1940 -
5.1941 - 'getBindings': function(node, bindingContext) {
5.1942 - var bindingsString = this['getBindingsString'](node, bindingContext);
5.1943 - return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
5.1944 - },
5.1945 -
5.1946 - // The following function is only used internally by this default provider.
5.1947 - // It's not part of the interface definition for a general binding provider.
5.1948 - 'getBindingsString': function(node, bindingContext) {
5.1949 - switch (node.nodeType) {
5.1950 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
5.1951 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
5.1952 - default: return null;
5.1953 - }
5.1954 - },
5.1955 -
5.1956 - // The following function is only used internally by this default provider.
5.1957 - // It's not part of the interface definition for a general binding provider.
5.1958 - 'parseBindingsString': function(bindingsString, bindingContext, node) {
5.1959 - try {
5.1960 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
5.1961 - return bindingFunction(bindingContext, node);
5.1962 - } catch (ex) {
5.1963 - throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
5.1964 - }
5.1965 - }
5.1966 - });
5.1967 -
5.1968 - ko.bindingProvider['instance'] = new ko.bindingProvider();
5.1969 -
5.1970 - function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
5.1971 - var cacheKey = bindingsString;
5.1972 - return cache[cacheKey]
5.1973 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
5.1974 - }
5.1975 -
5.1976 - function createBindingsStringEvaluator(bindingsString) {
5.1977 - // Build the source for a function that evaluates "expression"
5.1978 - // For each scope variable, add an extra level of "with" nesting
5.1979 - // Example result: with(sc1) { with(sc0) { return (expression) } }
5.1980 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
5.1981 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
5.1982 - return new Function("$context", "$element", functionBody);
5.1983 - }
5.1984 -})();
5.1985 -
5.1986 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
5.1987 -(function () {
5.1988 - ko.bindingHandlers = {};
5.1989 -
5.1990 - ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
5.1991 - if (parentBindingContext) {
5.1992 - ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
5.1993 - this['$parentContext'] = parentBindingContext;
5.1994 - this['$parent'] = parentBindingContext['$data'];
5.1995 - this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
5.1996 - this['$parents'].unshift(this['$parent']);
5.1997 - } else {
5.1998 - this['$parents'] = [];
5.1999 - this['$root'] = dataItem;
5.2000 - // Export 'ko' in the binding context so it will be available in bindings and templates
5.2001 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
5.2002 - // See https://github.com/SteveSanderson/knockout/issues/490
5.2003 - this['ko'] = ko;
5.2004 - }
5.2005 - this['$data'] = dataItem;
5.2006 - if (dataItemAlias)
5.2007 - this[dataItemAlias] = dataItem;
5.2008 - }
5.2009 - ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
5.2010 - return new ko.bindingContext(dataItem, this, dataItemAlias);
5.2011 - };
5.2012 - ko.bindingContext.prototype['extend'] = function(properties) {
5.2013 - var clone = ko.utils.extend(new ko.bindingContext(), this);
5.2014 - return ko.utils.extend(clone, properties);
5.2015 - };
5.2016 -
5.2017 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
5.2018 - var validator = ko.virtualElements.allowedBindings[bindingName];
5.2019 - if (!validator)
5.2020 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
5.2021 - }
5.2022 -
5.2023 - function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
5.2024 - var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
5.2025 - while (currentChild = nextInQueue) {
5.2026 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
5.2027 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
5.2028 - applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
5.2029 - }
5.2030 - }
5.2031 -
5.2032 - function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
5.2033 - var shouldBindDescendants = true;
5.2034 -
5.2035 - // Perf optimisation: Apply bindings only if...
5.2036 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
5.2037 - // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
5.2038 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
5.2039 - var isElement = (nodeVerified.nodeType === 1);
5.2040 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
5.2041 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
5.2042 -
5.2043 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
5.2044 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
5.2045 - if (shouldApplyBindings)
5.2046 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
5.2047 -
5.2048 - if (shouldBindDescendants) {
5.2049 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
5.2050 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
5.2051 - // hence bindingContextsMayDifferFromDomParentElement is false
5.2052 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
5.2053 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
5.2054 - // hence bindingContextsMayDifferFromDomParentElement is true
5.2055 - applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
5.2056 - }
5.2057 - }
5.2058 -
5.2059 - function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
5.2060 - // Need to be sure that inits are only run once, and updates never run until all the inits have been run
5.2061 - var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
5.2062 -
5.2063 - // Each time the dependentObservable is evaluated (after data changes),
5.2064 - // the binding attribute is reparsed so that it can pick out the correct
5.2065 - // model properties in the context of the changed data.
5.2066 - // DOM event callbacks need to be able to access this changed data,
5.2067 - // so we need a single parsedBindings variable (shared by all callbacks
5.2068 - // associated with this node's bindings) that all the closures can access.
5.2069 - var parsedBindings;
5.2070 - function makeValueAccessor(bindingKey) {
5.2071 - return function () { return parsedBindings[bindingKey] }
5.2072 - }
5.2073 - function parsedBindingsAccessor() {
5.2074 - return parsedBindings;
5.2075 - }
5.2076 -
5.2077 - var bindingHandlerThatControlsDescendantBindings;
5.2078 - ko.dependentObservable(
5.2079 - function () {
5.2080 - // Ensure we have a nonnull binding context to work with
5.2081 - var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
5.2082 - ? viewModelOrBindingContext
5.2083 - : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
5.2084 - var viewModel = bindingContextInstance['$data'];
5.2085 -
5.2086 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
5.2087 - // we can easily recover it just by scanning up the node's ancestors in the DOM
5.2088 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
5.2089 - if (bindingContextMayDifferFromDomParentElement)
5.2090 - ko.storedBindingContextForNode(node, bindingContextInstance);
5.2091 -
5.2092 - // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
5.2093 - var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
5.2094 - parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
5.2095 -
5.2096 - if (parsedBindings) {
5.2097 - // First run all the inits, so bindings can register for notification on changes
5.2098 - if (initPhase === 0) {
5.2099 - initPhase = 1;
5.2100 - for (var bindingKey in parsedBindings) {
5.2101 - var binding = ko.bindingHandlers[bindingKey];
5.2102 - if (binding && node.nodeType === 8)
5.2103 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
5.2104 -
5.2105 - if (binding && typeof binding["init"] == "function") {
5.2106 - var handlerInitFn = binding["init"];
5.2107 - var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
5.2108 -
5.2109 - // If this binding handler claims to control descendant bindings, make a note of this
5.2110 - if (initResult && initResult['controlsDescendantBindings']) {
5.2111 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
5.2112 - 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.");
5.2113 - bindingHandlerThatControlsDescendantBindings = bindingKey;
5.2114 - }
5.2115 - }
5.2116 - }
5.2117 - initPhase = 2;
5.2118 - }
5.2119 -
5.2120 - // ... then run all the updates, which might trigger changes even on the first evaluation
5.2121 - if (initPhase === 2) {
5.2122 - for (var bindingKey in parsedBindings) {
5.2123 - var binding = ko.bindingHandlers[bindingKey];
5.2124 - if (binding && typeof binding["update"] == "function") {
5.2125 - var handlerUpdateFn = binding["update"];
5.2126 - handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
5.2127 - }
5.2128 - }
5.2129 - }
5.2130 - }
5.2131 - },
5.2132 - null,
5.2133 - { disposeWhenNodeIsRemoved : node }
5.2134 - );
5.2135 -
5.2136 - return {
5.2137 - shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
5.2138 - };
5.2139 - };
5.2140 -
5.2141 - var storedBindingContextDomDataKey = "__ko_bindingContext__";
5.2142 - ko.storedBindingContextForNode = function (node, bindingContext) {
5.2143 - if (arguments.length == 2)
5.2144 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
5.2145 - else
5.2146 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
5.2147 - }
5.2148 -
5.2149 - ko.applyBindingsToNode = function (node, bindings, viewModel) {
5.2150 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
5.2151 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
5.2152 - return applyBindingsToNodeInternal(node, bindings, viewModel, true);
5.2153 - };
5.2154 -
5.2155 - ko.applyBindingsToDescendants = function(viewModel, rootNode) {
5.2156 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
5.2157 - applyBindingsToDescendantsInternal(viewModel, rootNode, true);
5.2158 - };
5.2159 -
5.2160 - ko.applyBindings = function (viewModel, rootNode) {
5.2161 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
5.2162 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
5.2163 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
5.2164 -
5.2165 - applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
5.2166 - };
5.2167 -
5.2168 - // Retrieving binding context from arbitrary nodes
5.2169 - ko.contextFor = function(node) {
5.2170 - // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
5.2171 - switch (node.nodeType) {
5.2172 - case 1:
5.2173 - case 8:
5.2174 - var context = ko.storedBindingContextForNode(node);
5.2175 - if (context) return context;
5.2176 - if (node.parentNode) return ko.contextFor(node.parentNode);
5.2177 - break;
5.2178 - }
5.2179 - return undefined;
5.2180 - };
5.2181 - ko.dataFor = function(node) {
5.2182 - var context = ko.contextFor(node);
5.2183 - return context ? context['$data'] : undefined;
5.2184 - };
5.2185 -
5.2186 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
5.2187 - ko.exportSymbol('applyBindings', ko.applyBindings);
5.2188 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
5.2189 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
5.2190 - ko.exportSymbol('contextFor', ko.contextFor);
5.2191 - ko.exportSymbol('dataFor', ko.dataFor);
5.2192 -})();
5.2193 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
5.2194 -ko.bindingHandlers['attr'] = {
5.2195 - 'update': function(element, valueAccessor, allBindingsAccessor) {
5.2196 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
5.2197 - for (var attrName in value) {
5.2198 - if (typeof attrName == "string") {
5.2199 - var attrValue = ko.utils.unwrapObservable(value[attrName]);
5.2200 -
5.2201 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
5.2202 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
5.2203 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
5.2204 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
5.2205 - if (toRemove)
5.2206 - element.removeAttribute(attrName);
5.2207 -
5.2208 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
5.2209 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
5.2210 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
5.2211 - // property for IE <= 8.
5.2212 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
5.2213 - attrName = attrHtmlToJavascriptMap[attrName];
5.2214 - if (toRemove)
5.2215 - element.removeAttribute(attrName);
5.2216 - else
5.2217 - element[attrName] = attrValue;
5.2218 - } else if (!toRemove) {
5.2219 - try {
5.2220 - element.setAttribute(attrName, attrValue.toString());
5.2221 - } catch (err) {
5.2222 - // ignore for now
5.2223 - if (console) {
5.2224 - console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
5.2225 - }
5.2226 - }
5.2227 - }
5.2228 -
5.2229 - // Treat "name" specially - although you can think of it as an attribute, it also needs
5.2230 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
5.2231 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
5.2232 - // entirely, and there's no strong reason to allow for such casing in HTML.
5.2233 - if (attrName === "name") {
5.2234 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
5.2235 - }
5.2236 - }
5.2237 - }
5.2238 - }
5.2239 -};
5.2240 -ko.bindingHandlers['checked'] = {
5.2241 - 'init': function (element, valueAccessor, allBindingsAccessor) {
5.2242 - var updateHandler = function() {
5.2243 - var valueToWrite;
5.2244 - if (element.type == "checkbox") {
5.2245 - valueToWrite = element.checked;
5.2246 - } else if ((element.type == "radio") && (element.checked)) {
5.2247 - valueToWrite = element.value;
5.2248 - } else {
5.2249 - return; // "checked" binding only responds to checkboxes and selected radio buttons
5.2250 - }
5.2251 -
5.2252 - var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
5.2253 - if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
5.2254 - // For checkboxes bound to an array, we add/remove the checkbox value to that array
5.2255 - // This works for both observable and non-observable arrays
5.2256 - var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
5.2257 - if (element.checked && (existingEntryIndex < 0))
5.2258 - modelValue.push(element.value);
5.2259 - else if ((!element.checked) && (existingEntryIndex >= 0))
5.2260 - modelValue.splice(existingEntryIndex, 1);
5.2261 - } else {
5.2262 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
5.2263 - }
5.2264 - };
5.2265 - ko.utils.registerEventHandler(element, "click", updateHandler);
5.2266 -
5.2267 - // IE 6 won't allow radio buttons to be selected unless they have a name
5.2268 - if ((element.type == "radio") && !element.name)
5.2269 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
5.2270 - },
5.2271 - 'update': function (element, valueAccessor) {
5.2272 - var value = ko.utils.unwrapObservable(valueAccessor());
5.2273 -
5.2274 - if (element.type == "checkbox") {
5.2275 - if (value instanceof Array) {
5.2276 - // When bound to an array, the checkbox being checked represents its value being present in that array
5.2277 - element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
5.2278 - } else {
5.2279 - // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
5.2280 - element.checked = value;
5.2281 - }
5.2282 - } else if (element.type == "radio") {
5.2283 - element.checked = (element.value == value);
5.2284 - }
5.2285 - }
5.2286 -};
5.2287 -var classesWrittenByBindingKey = '__ko__cssValue';
5.2288 -ko.bindingHandlers['css'] = {
5.2289 - 'update': function (element, valueAccessor) {
5.2290 - var value = ko.utils.unwrapObservable(valueAccessor());
5.2291 - if (typeof value == "object") {
5.2292 - for (var className in value) {
5.2293 - var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
5.2294 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
5.2295 - }
5.2296 - } else {
5.2297 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
5.2298 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
5.2299 - element[classesWrittenByBindingKey] = value;
5.2300 - ko.utils.toggleDomNodeCssClass(element, value, true);
5.2301 - }
5.2302 - }
5.2303 -};
5.2304 -ko.bindingHandlers['enable'] = {
5.2305 - 'update': function (element, valueAccessor) {
5.2306 - var value = ko.utils.unwrapObservable(valueAccessor());
5.2307 - if (value && element.disabled)
5.2308 - element.removeAttribute("disabled");
5.2309 - else if ((!value) && (!element.disabled))
5.2310 - element.disabled = true;
5.2311 - }
5.2312 -};
5.2313 -
5.2314 -ko.bindingHandlers['disable'] = {
5.2315 - 'update': function (element, valueAccessor) {
5.2316 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
5.2317 - }
5.2318 -};
5.2319 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
5.2320 -// e.g. click:handler instead of the usual full-length event:{click:handler}
5.2321 -function makeEventHandlerShortcut(eventName) {
5.2322 - ko.bindingHandlers[eventName] = {
5.2323 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
5.2324 - var newValueAccessor = function () {
5.2325 - var result = {};
5.2326 - result[eventName] = valueAccessor();
5.2327 - return result;
5.2328 - };
5.2329 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
5.2330 - }
5.2331 - }
5.2332 -}
5.2333 -
5.2334 -ko.bindingHandlers['event'] = {
5.2335 - 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
5.2336 - var eventsToHandle = valueAccessor() || {};
5.2337 - for(var eventNameOutsideClosure in eventsToHandle) {
5.2338 - (function() {
5.2339 - var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
5.2340 - if (typeof eventName == "string") {
5.2341 - ko.utils.registerEventHandler(element, eventName, function (event) {
5.2342 - var handlerReturnValue;
5.2343 - var handlerFunction = valueAccessor()[eventName];
5.2344 - if (!handlerFunction)
5.2345 - return;
5.2346 - var allBindings = allBindingsAccessor();
5.2347 -
5.2348 - try {
5.2349 - // Take all the event args, and prefix with the viewmodel
5.2350 - var argsForHandler = ko.utils.makeArray(arguments);
5.2351 - argsForHandler.unshift(viewModel);
5.2352 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
5.2353 - } finally {
5.2354 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
5.2355 - if (event.preventDefault)
5.2356 - event.preventDefault();
5.2357 - else
5.2358 - event.returnValue = false;
5.2359 - }
5.2360 - }
5.2361 -
5.2362 - var bubble = allBindings[eventName + 'Bubble'] !== false;
5.2363 - if (!bubble) {
5.2364 - event.cancelBubble = true;
5.2365 - if (event.stopPropagation)
5.2366 - event.stopPropagation();
5.2367 - }
5.2368 - });
5.2369 - }
5.2370 - })();
5.2371 - }
5.2372 - }
5.2373 -};
5.2374 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
5.2375 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
5.2376 -ko.bindingHandlers['foreach'] = {
5.2377 - makeTemplateValueAccessor: function(valueAccessor) {
5.2378 - return function() {
5.2379 - var modelValue = valueAccessor(),
5.2380 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
5.2381 -
5.2382 - // If unwrappedValue is the array, pass in the wrapped value on its own
5.2383 - // The value will be unwrapped and tracked within the template binding
5.2384 - // (See https://github.com/SteveSanderson/knockout/issues/523)
5.2385 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
5.2386 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
5.2387 -
5.2388 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
5.2389 - ko.utils.unwrapObservable(modelValue);
5.2390 - return {
5.2391 - 'foreach': unwrappedValue['data'],
5.2392 - 'as': unwrappedValue['as'],
5.2393 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
5.2394 - 'afterAdd': unwrappedValue['afterAdd'],
5.2395 - 'beforeRemove': unwrappedValue['beforeRemove'],
5.2396 - 'afterRender': unwrappedValue['afterRender'],
5.2397 - 'beforeMove': unwrappedValue['beforeMove'],
5.2398 - 'afterMove': unwrappedValue['afterMove'],
5.2399 - 'templateEngine': ko.nativeTemplateEngine.instance
5.2400 - };
5.2401 - };
5.2402 - },
5.2403 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
5.2404 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
5.2405 - },
5.2406 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
5.2407 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
5.2408 - }
5.2409 -};
5.2410 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
5.2411 -ko.virtualElements.allowedBindings['foreach'] = true;
5.2412 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
5.2413 -ko.bindingHandlers['hasfocus'] = {
5.2414 - 'init': function(element, valueAccessor, allBindingsAccessor) {
5.2415 - var handleElementFocusChange = function(isFocused) {
5.2416 - // Where possible, ignore which event was raised and determine focus state using activeElement,
5.2417 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
5.2418 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
5.2419 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
5.2420 - // from calling 'blur()' on the element when it loses focus.
5.2421 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
5.2422 - element[hasfocusUpdatingProperty] = true;
5.2423 - var ownerDoc = element.ownerDocument;
5.2424 - if ("activeElement" in ownerDoc) {
5.2425 - isFocused = (ownerDoc.activeElement === element);
5.2426 - }
5.2427 - var modelValue = valueAccessor();
5.2428 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
5.2429 - element[hasfocusUpdatingProperty] = false;
5.2430 - };
5.2431 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
5.2432 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
5.2433 -
5.2434 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
5.2435 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
5.2436 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
5.2437 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
5.2438 - },
5.2439 - 'update': function(element, valueAccessor) {
5.2440 - var value = ko.utils.unwrapObservable(valueAccessor());
5.2441 - if (!element[hasfocusUpdatingProperty]) {
5.2442 - value ? element.focus() : element.blur();
5.2443 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
5.2444 - }
5.2445 - }
5.2446 -};
5.2447 -ko.bindingHandlers['html'] = {
5.2448 - 'init': function() {
5.2449 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
5.2450 - return { 'controlsDescendantBindings': true };
5.2451 - },
5.2452 - 'update': function (element, valueAccessor) {
5.2453 - // setHtml will unwrap the value if needed
5.2454 - ko.utils.setHtml(element, valueAccessor());
5.2455 - }
5.2456 -};
5.2457 -var withIfDomDataKey = '__ko_withIfBindingData';
5.2458 -// Makes a binding like with or if
5.2459 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
5.2460 - ko.bindingHandlers[bindingKey] = {
5.2461 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
5.2462 - ko.utils.domData.set(element, withIfDomDataKey, {});
5.2463 - return { 'controlsDescendantBindings': true };
5.2464 - },
5.2465 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
5.2466 - var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
5.2467 - dataValue = ko.utils.unwrapObservable(valueAccessor()),
5.2468 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
5.2469 - isFirstRender = !withIfData.savedNodes,
5.2470 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
5.2471 -
5.2472 - if (needsRefresh) {
5.2473 - if (isFirstRender) {
5.2474 - withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
5.2475 - }
5.2476 -
5.2477 - if (shouldDisplay) {
5.2478 - if (!isFirstRender) {
5.2479 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
5.2480 - }
5.2481 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
5.2482 - } else {
5.2483 - ko.virtualElements.emptyNode(element);
5.2484 - }
5.2485 -
5.2486 - withIfData.didDisplayOnLastUpdate = shouldDisplay;
5.2487 - }
5.2488 - }
5.2489 - };
5.2490 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
5.2491 - ko.virtualElements.allowedBindings[bindingKey] = true;
5.2492 -}
5.2493 -
5.2494 -// Construct the actual binding handlers
5.2495 -makeWithIfBinding('if');
5.2496 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
5.2497 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
5.2498 - function(bindingContext, dataValue) {
5.2499 - return bindingContext['createChildContext'](dataValue);
5.2500 - }
5.2501 -);
5.2502 -function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
5.2503 - if (preferModelValue) {
5.2504 - if (modelValue !== ko.selectExtensions.readValue(element))
5.2505 - ko.selectExtensions.writeValue(element, modelValue);
5.2506 - }
5.2507 -
5.2508 - // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
5.2509 - // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
5.2510 - // change the model value to match the dropdown.
5.2511 - if (modelValue !== ko.selectExtensions.readValue(element))
5.2512 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
5.2513 -};
5.2514 -
5.2515 -ko.bindingHandlers['options'] = {
5.2516 - 'update': function (element, valueAccessor, allBindingsAccessor) {
5.2517 - if (ko.utils.tagNameLower(element) !== "select")
5.2518 - throw new Error("options binding applies only to SELECT elements");
5.2519 -
5.2520 - var selectWasPreviouslyEmpty = element.length == 0;
5.2521 - var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
5.2522 - return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
5.2523 - }), function (node) {
5.2524 - return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
5.2525 - });
5.2526 - var previousScrollTop = element.scrollTop;
5.2527 -
5.2528 - var value = ko.utils.unwrapObservable(valueAccessor());
5.2529 - var selectedValue = element.value;
5.2530 -
5.2531 - // Remove all existing <option>s.
5.2532 - // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
5.2533 - while (element.length > 0) {
5.2534 - ko.cleanNode(element.options[0]);
5.2535 - element.remove(0);
5.2536 - }
5.2537 -
5.2538 - if (value) {
5.2539 - var allBindings = allBindingsAccessor(),
5.2540 - includeDestroyed = allBindings['optionsIncludeDestroyed'];
5.2541 -
5.2542 - if (typeof value.length != "number")
5.2543 - value = [value];
5.2544 - if (allBindings['optionsCaption']) {
5.2545 - var option = document.createElement("option");
5.2546 - ko.utils.setHtml(option, allBindings['optionsCaption']);
5.2547 - ko.selectExtensions.writeValue(option, undefined);
5.2548 - element.appendChild(option);
5.2549 - }
5.2550 -
5.2551 - for (var i = 0, j = value.length; i < j; i++) {
5.2552 - // Skip destroyed items
5.2553 - var arrayEntry = value[i];
5.2554 - if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
5.2555 - continue;
5.2556 -
5.2557 - var option = document.createElement("option");
5.2558 -
5.2559 - function applyToObject(object, predicate, defaultValue) {
5.2560 - var predicateType = typeof predicate;
5.2561 - if (predicateType == "function") // Given a function; run it against the data value
5.2562 - return predicate(object);
5.2563 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
5.2564 - return object[predicate];
5.2565 - else // Given no optionsText arg; use the data value itself
5.2566 - return defaultValue;
5.2567 - }
5.2568 -
5.2569 - // Apply a value to the option element
5.2570 - var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
5.2571 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
5.2572 -
5.2573 - // Apply some text to the option element
5.2574 - var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
5.2575 - ko.utils.setTextContent(option, optionText);
5.2576 -
5.2577 - element.appendChild(option);
5.2578 - }
5.2579 -
5.2580 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
5.2581 - // That's why we first added them without selection. Now it's time to set the selection.
5.2582 - var newOptions = element.getElementsByTagName("option");
5.2583 - var countSelectionsRetained = 0;
5.2584 - for (var i = 0, j = newOptions.length; i < j; i++) {
5.2585 - if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
5.2586 - ko.utils.setOptionNodeSelectionState(newOptions[i], true);
5.2587 - countSelectionsRetained++;
5.2588 - }
5.2589 - }
5.2590 -
5.2591 - element.scrollTop = previousScrollTop;
5.2592 -
5.2593 - if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
5.2594 - // Ensure consistency between model value and selected option.
5.2595 - // If the dropdown is being populated for the first time here (or was otherwise previously empty),
5.2596 - // the dropdown selection state is meaningless, so we preserve the model value.
5.2597 - ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
5.2598 - }
5.2599 -
5.2600 - // Workaround for IE9 bug
5.2601 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
5.2602 - }
5.2603 - }
5.2604 -};
5.2605 -ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
5.2606 -ko.bindingHandlers['selectedOptions'] = {
5.2607 - 'init': function (element, valueAccessor, allBindingsAccessor) {
5.2608 - ko.utils.registerEventHandler(element, "change", function () {
5.2609 - var value = valueAccessor(), valueToWrite = [];
5.2610 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
5.2611 - if (node.selected)
5.2612 - valueToWrite.push(ko.selectExtensions.readValue(node));
5.2613 - });
5.2614 - ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
5.2615 - });
5.2616 - },
5.2617 - 'update': function (element, valueAccessor) {
5.2618 - if (ko.utils.tagNameLower(element) != "select")
5.2619 - throw new Error("values binding applies only to SELECT elements");
5.2620 -
5.2621 - var newValue = ko.utils.unwrapObservable(valueAccessor());
5.2622 - if (newValue && typeof newValue.length == "number") {
5.2623 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
5.2624 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
5.2625 - ko.utils.setOptionNodeSelectionState(node, isSelected);
5.2626 - });
5.2627 - }
5.2628 - }
5.2629 -};
5.2630 -ko.bindingHandlers['style'] = {
5.2631 - 'update': function (element, valueAccessor) {
5.2632 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
5.2633 - for (var styleName in value) {
5.2634 - if (typeof styleName == "string") {
5.2635 - var styleValue = ko.utils.unwrapObservable(value[styleName]);
5.2636 - element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
5.2637 - }
5.2638 - }
5.2639 - }
5.2640 -};
5.2641 -ko.bindingHandlers['submit'] = {
5.2642 - 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
5.2643 - if (typeof valueAccessor() != "function")
5.2644 - throw new Error("The value for a submit binding must be a function");
5.2645 - ko.utils.registerEventHandler(element, "submit", function (event) {
5.2646 - var handlerReturnValue;
5.2647 - var value = valueAccessor();
5.2648 - try { handlerReturnValue = value.call(viewModel, element); }
5.2649 - finally {
5.2650 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
5.2651 - if (event.preventDefault)
5.2652 - event.preventDefault();
5.2653 - else
5.2654 - event.returnValue = false;
5.2655 - }
5.2656 - }
5.2657 - });
5.2658 - }
5.2659 -};
5.2660 -ko.bindingHandlers['text'] = {
5.2661 - 'update': function (element, valueAccessor) {
5.2662 - ko.utils.setTextContent(element, valueAccessor());
5.2663 - }
5.2664 -};
5.2665 -ko.virtualElements.allowedBindings['text'] = true;
5.2666 -ko.bindingHandlers['uniqueName'] = {
5.2667 - 'init': function (element, valueAccessor) {
5.2668 - if (valueAccessor()) {
5.2669 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
5.2670 - ko.utils.setElementName(element, name);
5.2671 - }
5.2672 - }
5.2673 -};
5.2674 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
5.2675 -ko.bindingHandlers['value'] = {
5.2676 - 'init': function (element, valueAccessor, allBindingsAccessor) {
5.2677 - // Always catch "change" event; possibly other events too if asked
5.2678 - var eventsToCatch = ["change"];
5.2679 - var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
5.2680 - var propertyChangedFired = false;
5.2681 - if (requestedEventsToCatch) {
5.2682 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
5.2683 - requestedEventsToCatch = [requestedEventsToCatch];
5.2684 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
5.2685 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
5.2686 - }
5.2687 -
5.2688 - var valueUpdateHandler = function() {
5.2689 - propertyChangedFired = false;
5.2690 - var modelValue = valueAccessor();
5.2691 - var elementValue = ko.selectExtensions.readValue(element);
5.2692 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
5.2693 - }
5.2694 -
5.2695 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
5.2696 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
5.2697 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
5.2698 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
5.2699 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
5.2700 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
5.2701 - ko.utils.registerEventHandler(element, "blur", function() {
5.2702 - if (propertyChangedFired) {
5.2703 - valueUpdateHandler();
5.2704 - }
5.2705 - });
5.2706 - }
5.2707 -
5.2708 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
5.2709 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
5.2710 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
5.2711 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
5.2712 - var handler = valueUpdateHandler;
5.2713 - if (ko.utils.stringStartsWith(eventName, "after")) {
5.2714 - handler = function() { setTimeout(valueUpdateHandler, 0) };
5.2715 - eventName = eventName.substring("after".length);
5.2716 - }
5.2717 - ko.utils.registerEventHandler(element, eventName, handler);
5.2718 - });
5.2719 - },
5.2720 - 'update': function (element, valueAccessor) {
5.2721 - var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
5.2722 - var newValue = ko.utils.unwrapObservable(valueAccessor());
5.2723 - var elementValue = ko.selectExtensions.readValue(element);
5.2724 - var valueHasChanged = (newValue != elementValue);
5.2725 -
5.2726 - // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same).
5.2727 - // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here.
5.2728 - if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
5.2729 - valueHasChanged = true;
5.2730 -
5.2731 - if (valueHasChanged) {
5.2732 - var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
5.2733 - applyValueAction();
5.2734 -
5.2735 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
5.2736 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
5.2737 - // to apply the value as well.
5.2738 - var alsoApplyAsynchronously = valueIsSelectOption;
5.2739 - if (alsoApplyAsynchronously)
5.2740 - setTimeout(applyValueAction, 0);
5.2741 - }
5.2742 -
5.2743 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
5.2744 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
5.2745 - if (valueIsSelectOption && (element.length > 0))
5.2746 - ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
5.2747 - }
5.2748 -};
5.2749 -ko.bindingHandlers['visible'] = {
5.2750 - 'update': function (element, valueAccessor) {
5.2751 - var value = ko.utils.unwrapObservable(valueAccessor());
5.2752 - var isCurrentlyVisible = !(element.style.display == "none");
5.2753 - if (value && !isCurrentlyVisible)
5.2754 - element.style.display = "";
5.2755 - else if ((!value) && isCurrentlyVisible)
5.2756 - element.style.display = "none";
5.2757 - }
5.2758 -};
5.2759 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
5.2760 -makeEventHandlerShortcut('click');
5.2761 -// If you want to make a custom template engine,
5.2762 -//
5.2763 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
5.2764 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
5.2765 -//
5.2766 -// function (templateSource, bindingContext, options) {
5.2767 -// // - templateSource.text() is the text of the template you should render
5.2768 -// // - bindingContext.$data is the data you should pass into the template
5.2769 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
5.2770 -// // and bindingContext.$root available in the template too
5.2771 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
5.2772 -// //
5.2773 -// // Return value: an array of DOM nodes
5.2774 -// }
5.2775 -//
5.2776 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
5.2777 -//
5.2778 -// function (script) {
5.2779 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
5.2780 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
5.2781 -// }
5.2782 -//
5.2783 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
5.2784 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
5.2785 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
5.2786 -
5.2787 -ko.templateEngine = function () { };
5.2788 -
5.2789 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
5.2790 - throw new Error("Override renderTemplateSource");
5.2791 -};
5.2792 -
5.2793 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
5.2794 - throw new Error("Override createJavaScriptEvaluatorBlock");
5.2795 -};
5.2796 -
5.2797 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
5.2798 - // Named template
5.2799 - if (typeof template == "string") {
5.2800 - templateDocument = templateDocument || document;
5.2801 - var elem = templateDocument.getElementById(template);
5.2802 - if (!elem)
5.2803 - throw new Error("Cannot find template with ID " + template);
5.2804 - return new ko.templateSources.domElement(elem);
5.2805 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
5.2806 - // Anonymous template
5.2807 - return new ko.templateSources.anonymousTemplate(template);
5.2808 - } else
5.2809 - throw new Error("Unknown template type: " + template);
5.2810 -};
5.2811 -
5.2812 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
5.2813 - var templateSource = this['makeTemplateSource'](template, templateDocument);
5.2814 - return this['renderTemplateSource'](templateSource, bindingContext, options);
5.2815 -};
5.2816 -
5.2817 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
5.2818 - // Skip rewriting if requested
5.2819 - if (this['allowTemplateRewriting'] === false)
5.2820 - return true;
5.2821 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
5.2822 -};
5.2823 -
5.2824 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
5.2825 - var templateSource = this['makeTemplateSource'](template, templateDocument);
5.2826 - var rewritten = rewriterCallback(templateSource['text']());
5.2827 - templateSource['text'](rewritten);
5.2828 - templateSource['data']("isRewritten", true);
5.2829 -};
5.2830 -
5.2831 -ko.exportSymbol('templateEngine', ko.templateEngine);
5.2832 -
5.2833 -ko.templateRewriting = (function () {
5.2834 - var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
5.2835 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
5.2836 -
5.2837 - function validateDataBindValuesForRewriting(keyValueArray) {
5.2838 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
5.2839 - for (var i = 0; i < keyValueArray.length; i++) {
5.2840 - var key = keyValueArray[i]['key'];
5.2841 - if (allValidators.hasOwnProperty(key)) {
5.2842 - var validator = allValidators[key];
5.2843 -
5.2844 - if (typeof validator === "function") {
5.2845 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
5.2846 - if (possibleErrorMessage)
5.2847 - throw new Error(possibleErrorMessage);
5.2848 - } else if (!validator) {
5.2849 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
5.2850 - }
5.2851 - }
5.2852 - }
5.2853 - }
5.2854 -
5.2855 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
5.2856 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
5.2857 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
5.2858 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
5.2859 -
5.2860 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
5.2861 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
5.2862 - // extra indirection.
5.2863 - var applyBindingsToNextSiblingScript =
5.2864 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
5.2865 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
5.2866 - }
5.2867 -
5.2868 - return {
5.2869 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
5.2870 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
5.2871 - templateEngine['rewriteTemplate'](template, function (htmlString) {
5.2872 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
5.2873 - }, templateDocument);
5.2874 - },
5.2875 -
5.2876 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
5.2877 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
5.2878 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
5.2879 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
5.2880 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
5.2881 - });
5.2882 - },
5.2883 -
5.2884 - applyMemoizedBindingsToNextSibling: function (bindings) {
5.2885 - return ko.memoization.memoize(function (domNode, bindingContext) {
5.2886 - if (domNode.nextSibling)
5.2887 - ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
5.2888 - });
5.2889 - }
5.2890 - }
5.2891 -})();
5.2892 -
5.2893 -
5.2894 -// Exported only because it has to be referenced by string lookup from within rewritten template
5.2895 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
5.2896 -(function() {
5.2897 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
5.2898 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
5.2899 - //
5.2900 - // Two are provided by default:
5.2901 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
5.2902 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
5.2903 - // without reading/writing the actual element text content, since it will be overwritten
5.2904 - // with the rendered template output.
5.2905 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
5.2906 - // Template sources need to have the following functions:
5.2907 - // text() - returns the template text from your storage location
5.2908 - // text(value) - writes the supplied template text to your storage location
5.2909 - // data(key) - reads values stored using data(key, value) - see below
5.2910 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
5.2911 - //
5.2912 - // Optionally, template sources can also have the following functions:
5.2913 - // nodes() - returns a DOM element containing the nodes of this template, where available
5.2914 - // nodes(value) - writes the given DOM element to your storage location
5.2915 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
5.2916 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
5.2917 - //
5.2918 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
5.2919 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
5.2920 -
5.2921 - ko.templateSources = {};
5.2922 -
5.2923 - // ---- ko.templateSources.domElement -----
5.2924 -
5.2925 - ko.templateSources.domElement = function(element) {
5.2926 - this.domElement = element;
5.2927 - }
5.2928 -
5.2929 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
5.2930 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
5.2931 - elemContentsProperty = tagNameLower === "script" ? "text"
5.2932 - : tagNameLower === "textarea" ? "value"
5.2933 - : "innerHTML";
5.2934 -
5.2935 - if (arguments.length == 0) {
5.2936 - return this.domElement[elemContentsProperty];
5.2937 - } else {
5.2938 - var valueToWrite = arguments[0];
5.2939 - if (elemContentsProperty === "innerHTML")
5.2940 - ko.utils.setHtml(this.domElement, valueToWrite);
5.2941 - else
5.2942 - this.domElement[elemContentsProperty] = valueToWrite;
5.2943 - }
5.2944 - };
5.2945 -
5.2946 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
5.2947 - if (arguments.length === 1) {
5.2948 - return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
5.2949 - } else {
5.2950 - ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
5.2951 - }
5.2952 - };
5.2953 -
5.2954 - // ---- ko.templateSources.anonymousTemplate -----
5.2955 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
5.2956 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
5.2957 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
5.2958 -
5.2959 - var anonymousTemplatesDomDataKey = "__ko_anon_template__";
5.2960 - ko.templateSources.anonymousTemplate = function(element) {
5.2961 - this.domElement = element;
5.2962 - }
5.2963 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
5.2964 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
5.2965 - if (arguments.length == 0) {
5.2966 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
5.2967 - if (templateData.textData === undefined && templateData.containerData)
5.2968 - templateData.textData = templateData.containerData.innerHTML;
5.2969 - return templateData.textData;
5.2970 - } else {
5.2971 - var valueToWrite = arguments[0];
5.2972 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
5.2973 - }
5.2974 - };
5.2975 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
5.2976 - if (arguments.length == 0) {
5.2977 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
5.2978 - return templateData.containerData;
5.2979 - } else {
5.2980 - var valueToWrite = arguments[0];
5.2981 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
5.2982 - }
5.2983 - };
5.2984 -
5.2985 - ko.exportSymbol('templateSources', ko.templateSources);
5.2986 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
5.2987 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
5.2988 -})();
5.2989 -(function () {
5.2990 - var _templateEngine;
5.2991 - ko.setTemplateEngine = function (templateEngine) {
5.2992 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
5.2993 - throw new Error("templateEngine must inherit from ko.templateEngine");
5.2994 - _templateEngine = templateEngine;
5.2995 - }
5.2996 -
5.2997 - function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
5.2998 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
5.2999 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
5.3000 - nextInQueue = ko.virtualElements.nextSibling(node);
5.3001 - if (node.nodeType === 1 || node.nodeType === 8)
5.3002 - action(node);
5.3003 - }
5.3004 - }
5.3005 -
5.3006 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
5.3007 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
5.3008 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
5.3009 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
5.3010 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
5.3011 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
5.3012 -
5.3013 - if (continuousNodeArray.length) {
5.3014 - var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
5.3015 -
5.3016 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
5.3017 - // whereas a regular applyBindings won't introduce new memoized nodes
5.3018 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
5.3019 - ko.applyBindings(bindingContext, node);
5.3020 - });
5.3021 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
5.3022 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
5.3023 - });
5.3024 - }
5.3025 - }
5.3026 -
5.3027 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
5.3028 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
5.3029 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
5.3030 - : null;
5.3031 - }
5.3032 -
5.3033 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
5.3034 - options = options || {};
5.3035 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
5.3036 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
5.3037 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
5.3038 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
5.3039 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
5.3040 -
5.3041 - // Loosely check result is an array of DOM nodes
5.3042 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
5.3043 - throw new Error("Template engine must return an array of DOM nodes");
5.3044 -
5.3045 - var haveAddedNodesToParent = false;
5.3046 - switch (renderMode) {
5.3047 - case "replaceChildren":
5.3048 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
5.3049 - haveAddedNodesToParent = true;
5.3050 - break;
5.3051 - case "replaceNode":
5.3052 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
5.3053 - haveAddedNodesToParent = true;
5.3054 - break;
5.3055 - case "ignoreTargetNode": break;
5.3056 - default:
5.3057 - throw new Error("Unknown renderMode: " + renderMode);
5.3058 - }
5.3059 -
5.3060 - if (haveAddedNodesToParent) {
5.3061 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
5.3062 - if (options['afterRender'])
5.3063 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
5.3064 - }
5.3065 -
5.3066 - return renderedNodesArray;
5.3067 - }
5.3068 -
5.3069 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
5.3070 - options = options || {};
5.3071 - if ((options['templateEngine'] || _templateEngine) == undefined)
5.3072 - throw new Error("Set a template engine before calling renderTemplate");
5.3073 - renderMode = renderMode || "replaceChildren";
5.3074 -
5.3075 - if (targetNodeOrNodeArray) {
5.3076 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
5.3077 -
5.3078 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
5.3079 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
5.3080 -
5.3081 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
5.3082 - function () {
5.3083 - // Ensure we've got a proper binding context to work with
5.3084 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
5.3085 - ? dataOrBindingContext
5.3086 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
5.3087 -
5.3088 - // Support selecting template as a function of the data being rendered
5.3089 - var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
5.3090 -
5.3091 - var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
5.3092 - if (renderMode == "replaceNode") {
5.3093 - targetNodeOrNodeArray = renderedNodesArray;
5.3094 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
5.3095 - }
5.3096 - },
5.3097 - null,
5.3098 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
5.3099 - );
5.3100 - } else {
5.3101 - // 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
5.3102 - return ko.memoization.memoize(function (domNode) {
5.3103 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
5.3104 - });
5.3105 - }
5.3106 - };
5.3107 -
5.3108 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
5.3109 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
5.3110 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
5.3111 - var arrayItemContext;
5.3112 -
5.3113 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
5.3114 - var executeTemplateForArrayItem = function (arrayValue, index) {
5.3115 - // Support selecting template as a function of the data being rendered
5.3116 - arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
5.3117 - arrayItemContext['$index'] = index;
5.3118 - var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
5.3119 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
5.3120 - }
5.3121 -
5.3122 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
5.3123 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
5.3124 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
5.3125 - if (options['afterRender'])
5.3126 - options['afterRender'](addedNodesArray, arrayValue);
5.3127 - };
5.3128 -
5.3129 - return ko.dependentObservable(function () {
5.3130 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
5.3131 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
5.3132 - unwrappedArray = [unwrappedArray];
5.3133 -
5.3134 - // Filter out any entries marked as destroyed
5.3135 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
5.3136 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
5.3137 - });
5.3138 -
5.3139 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
5.3140 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
5.3141 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
5.3142 -
5.3143 - }, null, { disposeWhenNodeIsRemoved: targetNode });
5.3144 - };
5.3145 -
5.3146 - var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
5.3147 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
5.3148 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
5.3149 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
5.3150 - oldComputed.dispose();
5.3151 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
5.3152 - }
5.3153 -
5.3154 - ko.bindingHandlers['template'] = {
5.3155 - 'init': function(element, valueAccessor) {
5.3156 - // Support anonymous templates
5.3157 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
5.3158 - if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
5.3159 - // It's an anonymous template - store the element contents, then clear the element
5.3160 - var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
5.3161 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
5.3162 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
5.3163 - }
5.3164 - return { 'controlsDescendantBindings': true };
5.3165 - },
5.3166 - 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
5.3167 - var templateName = ko.utils.unwrapObservable(valueAccessor()),
5.3168 - options = {},
5.3169 - shouldDisplay = true,
5.3170 - dataValue,
5.3171 - templateComputed = null;
5.3172 -
5.3173 - if (typeof templateName != "string") {
5.3174 - options = templateName;
5.3175 - templateName = options['name'];
5.3176 -
5.3177 - // Support "if"/"ifnot" conditions
5.3178 - if ('if' in options)
5.3179 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
5.3180 - if (shouldDisplay && 'ifnot' in options)
5.3181 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
5.3182 -
5.3183 - dataValue = ko.utils.unwrapObservable(options['data']);
5.3184 - }
5.3185 -
5.3186 - if ('foreach' in options) {
5.3187 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
5.3188 - var dataArray = (shouldDisplay && options['foreach']) || [];
5.3189 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
5.3190 - } else if (!shouldDisplay) {
5.3191 - ko.virtualElements.emptyNode(element);
5.3192 - } else {
5.3193 - // Render once for this single data point (or use the viewModel if no data was provided)
5.3194 - var innerBindingContext = ('data' in options) ?
5.3195 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
5.3196 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
5.3197 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
5.3198 - }
5.3199 -
5.3200 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
5.3201 - disposeOldComputedAndStoreNewOne(element, templateComputed);
5.3202 - }
5.3203 - };
5.3204 -
5.3205 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
5.3206 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
5.3207 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
5.3208 -
5.3209 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
5.3210 - return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
5.3211 -
5.3212 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
5.3213 - return null; // Named templates can be rewritten, so return "no error"
5.3214 - return "This template engine does not support anonymous templates nested within its templates";
5.3215 - };
5.3216 -
5.3217 - ko.virtualElements.allowedBindings['template'] = true;
5.3218 -})();
5.3219 -
5.3220 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
5.3221 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
5.3222 -
5.3223 -ko.utils.compareArrays = (function () {
5.3224 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
5.3225 -
5.3226 - // Simple calculation based on Levenshtein distance.
5.3227 - function compareArrays(oldArray, newArray, dontLimitMoves) {
5.3228 - oldArray = oldArray || [];
5.3229 - newArray = newArray || [];
5.3230 -
5.3231 - if (oldArray.length <= newArray.length)
5.3232 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
5.3233 - else
5.3234 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
5.3235 - }
5.3236 -
5.3237 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
5.3238 - var myMin = Math.min,
5.3239 - myMax = Math.max,
5.3240 - editDistanceMatrix = [],
5.3241 - smlIndex, smlIndexMax = smlArray.length,
5.3242 - bigIndex, bigIndexMax = bigArray.length,
5.3243 - compareRange = (bigIndexMax - smlIndexMax) || 1,
5.3244 - maxDistance = smlIndexMax + bigIndexMax + 1,
5.3245 - thisRow, lastRow,
5.3246 - bigIndexMaxForRow, bigIndexMinForRow;
5.3247 -
5.3248 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
5.3249 - lastRow = thisRow;
5.3250 - editDistanceMatrix.push(thisRow = []);
5.3251 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
5.3252 - bigIndexMinForRow = myMax(0, smlIndex - 1);
5.3253 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
5.3254 - if (!bigIndex)
5.3255 - thisRow[bigIndex] = smlIndex + 1;
5.3256 - else if (!smlIndex) // Top row - transform empty array into new array via additions
5.3257 - thisRow[bigIndex] = bigIndex + 1;
5.3258 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
5.3259 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
5.3260 - else {
5.3261 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
5.3262 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
5.3263 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
5.3264 - }
5.3265 - }
5.3266 - }
5.3267 -
5.3268 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
5.3269 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
5.3270 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
5.3271 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
5.3272 - notInSml.push(editScript[editScript.length] = { // added
5.3273 - 'status': statusNotInSml,
5.3274 - 'value': bigArray[--bigIndex],
5.3275 - 'index': bigIndex });
5.3276 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
5.3277 - notInBig.push(editScript[editScript.length] = { // deleted
5.3278 - 'status': statusNotInBig,
5.3279 - 'value': smlArray[--smlIndex],
5.3280 - 'index': smlIndex });
5.3281 - } else {
5.3282 - editScript.push({
5.3283 - 'status': "retained",
5.3284 - 'value': bigArray[--bigIndex] });
5.3285 - --smlIndex;
5.3286 - }
5.3287 - }
5.3288 -
5.3289 - if (notInSml.length && notInBig.length) {
5.3290 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
5.3291 - // smlIndexMax keeps the time complexity of this algorithm linear.
5.3292 - var limitFailedCompares = smlIndexMax * 10, failedCompares,
5.3293 - a, d, notInSmlItem, notInBigItem;
5.3294 - // Go through the items that have been added and deleted and try to find matches between them.
5.3295 - for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
5.3296 - for (d = 0; notInBigItem = notInBig[d]; d++) {
5.3297 - if (notInSmlItem['value'] === notInBigItem['value']) {
5.3298 - notInSmlItem['moved'] = notInBigItem['index'];
5.3299 - notInBigItem['moved'] = notInSmlItem['index'];
5.3300 - notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
5.3301 - failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
5.3302 - break;
5.3303 - }
5.3304 - }
5.3305 - failedCompares += d;
5.3306 - }
5.3307 - }
5.3308 - return editScript.reverse();
5.3309 - }
5.3310 -
5.3311 - return compareArrays;
5.3312 -})();
5.3313 -
5.3314 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
5.3315 -
5.3316 -(function () {
5.3317 - // Objective:
5.3318 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
5.3319 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
5.3320 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
5.3321 - // 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
5.3322 - // previously mapped - retain those nodes, and just insert/delete other ones
5.3323 -
5.3324 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
5.3325 - // You can use this, for example, to activate bindings on those nodes.
5.3326 -
5.3327 - function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
5.3328 - // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
5.3329 - // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
5.3330 - // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
5.3331 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
5.3332 - // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
5.3333 - //
5.3334 - // Rules:
5.3335 - // [A] Any leading nodes that aren't in the document any more should be ignored
5.3336 - // These most likely correspond to memoization nodes that were already removed during binding
5.3337 - // See https://github.com/SteveSanderson/knockout/pull/440
5.3338 - // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
5.3339 - // have already been removed, and include any nodes that have been inserted among the previous collection
5.3340 -
5.3341 - // Rule [A]
5.3342 - while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
5.3343 - contiguousNodeArray.splice(0, 1);
5.3344 -
5.3345 - // Rule [B]
5.3346 - if (contiguousNodeArray.length > 1) {
5.3347 - // Build up the actual new contiguous node set
5.3348 - var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
5.3349 - while (current !== last) {
5.3350 - current = current.nextSibling;
5.3351 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
5.3352 - return;
5.3353 - newContiguousSet.push(current);
5.3354 - }
5.3355 -
5.3356 - // ... then mutate the input array to match this.
5.3357 - // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
5.3358 - Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
5.3359 - }
5.3360 - return contiguousNodeArray;
5.3361 - }
5.3362 -
5.3363 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
5.3364 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
5.3365 - var mappedNodes = [];
5.3366 - var dependentObservable = ko.dependentObservable(function() {
5.3367 - var newMappedNodes = mapping(valueToMap, index) || [];
5.3368 -
5.3369 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
5.3370 - if (mappedNodes.length > 0) {
5.3371 - ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
5.3372 - if (callbackAfterAddingNodes)
5.3373 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
5.3374 - }
5.3375 -
5.3376 - // Replace the contents of the mappedNodes array, thereby updating the record
5.3377 - // of which nodes would be deleted if valueToMap was itself later removed
5.3378 - mappedNodes.splice(0, mappedNodes.length);
5.3379 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
5.3380 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
5.3381 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
5.3382 - }
5.3383 -
5.3384 - var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
5.3385 -
5.3386 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
5.3387 - // Compare the provided array against the previous one
5.3388 - array = array || [];
5.3389 - options = options || {};
5.3390 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
5.3391 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
5.3392 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
5.3393 - var editScript = ko.utils.compareArrays(lastArray, array);
5.3394 -
5.3395 - // Build the new mapping result
5.3396 - var newMappingResult = [];
5.3397 - var lastMappingResultIndex = 0;
5.3398 - var newMappingResultIndex = 0;
5.3399 -
5.3400 - var nodesToDelete = [];
5.3401 - var itemsToProcess = [];
5.3402 - var itemsForBeforeRemoveCallbacks = [];
5.3403 - var itemsForMoveCallbacks = [];
5.3404 - var itemsForAfterAddCallbacks = [];
5.3405 - var mapData;
5.3406 -
5.3407 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
5.3408 - mapData = lastMappingResult[oldPosition];
5.3409 - if (newMappingResultIndex !== oldPosition)
5.3410 - itemsForMoveCallbacks[editScriptIndex] = mapData;
5.3411 - // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
5.3412 - mapData.indexObservable(newMappingResultIndex++);
5.3413 - fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
5.3414 - newMappingResult.push(mapData);
5.3415 - itemsToProcess.push(mapData);
5.3416 - }
5.3417 -
5.3418 - function callCallback(callback, items) {
5.3419 - if (callback) {
5.3420 - for (var i = 0, n = items.length; i < n; i++) {
5.3421 - if (items[i]) {
5.3422 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
5.3423 - callback(node, i, items[i].arrayEntry);
5.3424 - });
5.3425 - }
5.3426 - }
5.3427 - }
5.3428 - }
5.3429 -
5.3430 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
5.3431 - movedIndex = editScriptItem['moved'];
5.3432 - switch (editScriptItem['status']) {
5.3433 - case "deleted":
5.3434 - if (movedIndex === undefined) {
5.3435 - mapData = lastMappingResult[lastMappingResultIndex];
5.3436 -
5.3437 - // Stop tracking changes to the mapping for these nodes
5.3438 - if (mapData.dependentObservable)
5.3439 - mapData.dependentObservable.dispose();
5.3440 -
5.3441 - // Queue these nodes for later removal
5.3442 - nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
5.3443 - if (options['beforeRemove']) {
5.3444 - itemsForBeforeRemoveCallbacks[i] = mapData;
5.3445 - itemsToProcess.push(mapData);
5.3446 - }
5.3447 - }
5.3448 - lastMappingResultIndex++;
5.3449 - break;
5.3450 -
5.3451 - case "retained":
5.3452 - itemMovedOrRetained(i, lastMappingResultIndex++);
5.3453 - break;
5.3454 -
5.3455 - case "added":
5.3456 - if (movedIndex !== undefined) {
5.3457 - itemMovedOrRetained(i, movedIndex);
5.3458 - } else {
5.3459 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
5.3460 - newMappingResult.push(mapData);
5.3461 - itemsToProcess.push(mapData);
5.3462 - if (!isFirstExecution)
5.3463 - itemsForAfterAddCallbacks[i] = mapData;
5.3464 - }
5.3465 - break;
5.3466 - }
5.3467 - }
5.3468 -
5.3469 - // Call beforeMove first before any changes have been made to the DOM
5.3470 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
5.3471 -
5.3472 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
5.3473 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
5.3474 -
5.3475 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
5.3476 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
5.3477 - // Get nodes for newly added items
5.3478 - if (!mapData.mappedNodes)
5.3479 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
5.3480 -
5.3481 - // Put nodes in the right place if they aren't there already
5.3482 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
5.3483 - if (node !== nextNode)
5.3484 - ko.virtualElements.insertAfter(domNode, node, lastNode);
5.3485 - }
5.3486 -
5.3487 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
5.3488 - if (!mapData.initialized && callbackAfterAddingNodes) {
5.3489 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
5.3490 - mapData.initialized = true;
5.3491 - }
5.3492 - }
5.3493 -
5.3494 - // If there's a beforeRemove callback, call it after reordering.
5.3495 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
5.3496 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
5.3497 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
5.3498 - // Perhaps we'll make that change in the future if this scenario becomes more common.
5.3499 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
5.3500 -
5.3501 - // Finally call afterMove and afterAdd callbacks
5.3502 - callCallback(options['afterMove'], itemsForMoveCallbacks);
5.3503 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
5.3504 -
5.3505 - // Store a copy of the array items we just considered so we can difference it next time
5.3506 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
5.3507 - }
5.3508 -})();
5.3509 -
5.3510 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
5.3511 -ko.nativeTemplateEngine = function () {
5.3512 - this['allowTemplateRewriting'] = false;
5.3513 -}
5.3514 -
5.3515 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
5.3516 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
5.3517 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
5.3518 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
5.3519 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
5.3520 -
5.3521 - if (templateNodes) {
5.3522 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
5.3523 - } else {
5.3524 - var templateText = templateSource['text']();
5.3525 - return ko.utils.parseHtmlFragment(templateText);
5.3526 - }
5.3527 -};
5.3528 -
5.3529 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
5.3530 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
5.3531 -
5.3532 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
5.3533 -(function() {
5.3534 - ko.jqueryTmplTemplateEngine = function () {
5.3535 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
5.3536 - // doesn't expose a version number, so we have to infer it.
5.3537 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
5.3538 - // which KO internally refers to as version "2", so older versions are no longer detected.
5.3539 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
5.3540 - if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
5.3541 - return 0;
5.3542 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
5.3543 - try {
5.3544 - if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
5.3545 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
5.3546 - return 2; // Final version of jquery.tmpl
5.3547 - }
5.3548 - } catch(ex) { /* Apparently not the version we were looking for */ }
5.3549 -
5.3550 - return 1; // Any older version that we don't support
5.3551 - })();
5.3552 -
5.3553 - function ensureHasReferencedJQueryTemplates() {
5.3554 - if (jQueryTmplVersion < 2)
5.3555 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
5.3556 - }
5.3557 -
5.3558 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
5.3559 - return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
5.3560 - }
5.3561 -
5.3562 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
5.3563 - options = options || {};
5.3564 - ensureHasReferencedJQueryTemplates();
5.3565 -
5.3566 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
5.3567 - var precompiled = templateSource['data']('precompiled');
5.3568 - if (!precompiled) {
5.3569 - var templateText = templateSource['text']() || "";
5.3570 - // Wrap in "with($whatever.koBindingContext) { ... }"
5.3571 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
5.3572 -
5.3573 - precompiled = jQuery['template'](null, templateText);
5.3574 - templateSource['data']('precompiled', precompiled);
5.3575 - }
5.3576 -
5.3577 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
5.3578 - var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
5.3579 -
5.3580 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
5.3581 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
5.3582 -
5.3583 - jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
5.3584 - return resultNodes;
5.3585 - };
5.3586 -
5.3587 - this['createJavaScriptEvaluatorBlock'] = function(script) {
5.3588 - return "{{ko_code ((function() { return " + script + " })()) }}";
5.3589 - };
5.3590 -
5.3591 - this['addTemplate'] = function(templateName, templateMarkup) {
5.3592 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
5.3593 - };
5.3594 -
5.3595 - if (jQueryTmplVersion > 0) {
5.3596 - jQuery['tmpl']['tag']['ko_code'] = {
5.3597 - open: "__.push($1 || '');"
5.3598 - };
5.3599 - jQuery['tmpl']['tag']['ko_with'] = {
5.3600 - open: "with($1) {",
5.3601 - close: "} "
5.3602 - };
5.3603 - }
5.3604 - };
5.3605 -
5.3606 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
5.3607 -
5.3608 - // Use this one by default *only if jquery.tmpl is referenced*
5.3609 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
5.3610 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
5.3611 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
5.3612 -
5.3613 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
5.3614 -})();
5.3615 -});
5.3616 -})(window,document,navigator,window["jQuery"]);
5.3617 -})();
5.3618 \ No newline at end of file
6.1 --- a/ko/bck2brwsr/src/test/java/org/apidesign/bck2brwsr/ko2brwsr/Bck2BrwsrKnockoutTest.java Mon Jan 06 13:45:57 2014 +0100
6.2 +++ b/ko/bck2brwsr/src/test/java/org/apidesign/bck2brwsr/ko2brwsr/Bck2BrwsrKnockoutTest.java Wed Jan 08 14:06:21 2014 +0100
6.3 @@ -31,6 +31,7 @@
6.4 import org.apidesign.html.json.spi.WSTransfer;
6.5 import org.apidesign.html.json.tck.KOTest;
6.6 import org.apidesign.html.json.tck.KnockoutTCK;
6.7 +import org.netbeans.html.kofx.FXContext;
6.8 import org.openide.util.lookup.ServiceProvider;
6.9 import org.testng.annotations.Factory;
6.10
6.11 @@ -53,7 +54,7 @@
6.12 return Contexts.newBuilder().
6.13 register(Transfer.class, BrwsrCtxImpl.DEFAULT, 9).
6.14 register(WSTransfer.class, BrwsrCtxImpl.DEFAULT, 9).
6.15 - register(Technology.class, BrwsrCtxImpl.DEFAULT, 9).build();
6.16 + register(Technology.class, new FXContext(null), 9).build();
6.17 }
6.18
6.19