Merge into the default line the use of stable 0.7 version of org.netbeans.html APIs
1.1 --- a/ko/archetype/src/main/resources/archetype-resources/pom.xml Wed Dec 11 08:22:17 2013 +0100
1.2 +++ b/ko/archetype/src/main/resources/archetype-resources/pom.xml Mon Jan 13 12:37:03 2014 +0100
1.3 @@ -126,7 +126,7 @@
1.4 <scope>test</scope>
1.5 </dependency>
1.6 <dependency>
1.7 - <groupId>org.apidesign.html</groupId>
1.8 + <groupId>org.netbeans.html</groupId>
1.9 <artifactId>net.java.html.json</artifactId>
1.10 <version>\${net.java.html.version}</version>
1.11 <type>jar</type>
1.12 @@ -182,8 +182,8 @@
1.13 </build>
1.14 <dependencies>
1.15 <dependency>
1.16 - <groupId>org.apidesign.html</groupId>
1.17 - <artifactId>ko-fx</artifactId>
1.18 + <groupId>org.netbeans.html</groupId>
1.19 + <artifactId>ko4j</artifactId>
1.20 <version>\${net.java.html.version}</version>
1.21 </dependency>
1.22 <dependency>
2.1 --- a/ko/bck2brwsr/pom.xml Wed Dec 11 08:22:17 2013 +0100
2.2 +++ b/ko/bck2brwsr/pom.xml Mon Jan 13 12:37:03 2014 +0100
2.3 @@ -62,6 +62,12 @@
2.4 <version>${project.version}</version>
2.5 <type>jar</type>
2.6 <scope>test</scope>
2.7 + <exclusions>
2.8 + <exclusion>
2.9 + <artifactId>json</artifactId>
2.10 + <groupId>org.json</groupId>
2.11 + </exclusion>
2.12 + </exclusions>
2.13 </dependency>
2.14 <dependency>
2.15 <groupId>org.apidesign.bck2brwsr</groupId>
2.16 @@ -74,14 +80,20 @@
2.17 <artifactId>launcher.http</artifactId>
2.18 <version>${project.version}</version>
2.19 <scope>test</scope>
2.20 + <exclusions>
2.21 + <exclusion>
2.22 + <artifactId>asm</artifactId>
2.23 + <groupId>org.ow2.asm</groupId>
2.24 + </exclusion>
2.25 + </exclusions>
2.26 </dependency>
2.27 <dependency>
2.28 - <groupId>org.apidesign.html</groupId>
2.29 + <groupId>org.netbeans.html</groupId>
2.30 <artifactId>net.java.html.json</artifactId>
2.31 <version>${net.java.html.version}</version>
2.32 </dependency>
2.33 <dependency>
2.34 - <groupId>org.apidesign.html</groupId>
2.35 + <groupId>org.netbeans.html</groupId>
2.36 <artifactId>net.java.html.json.tck</artifactId>
2.37 <version>${net.java.html.version}</version>
2.38 <scope>test</scope>
2.39 @@ -93,10 +105,31 @@
2.40 <type>jar</type>
2.41 </dependency>
2.42 <dependency>
2.43 - <groupId>org.apidesign.html</groupId>
2.44 + <groupId>org.netbeans.html</groupId>
2.45 <artifactId>net.java.html.boot</artifactId>
2.46 <version>${net.java.html.version}</version>
2.47 <type>jar</type>
2.48 + <exclusions>
2.49 + <exclusion>
2.50 + <artifactId>asm</artifactId>
2.51 + <groupId>org.ow2.asm</groupId>
2.52 + </exclusion>
2.53 + </exclusions>
2.54 + </dependency>
2.55 + <dependency>
2.56 + <groupId>org.netbeans.html</groupId>
2.57 + <artifactId>ko4j</artifactId>
2.58 + <version>${net.java.html.version}</version>
2.59 + <exclusions>
2.60 + <exclusion>
2.61 + <artifactId>json</artifactId>
2.62 + <groupId>org.json</groupId>
2.63 + </exclusion>
2.64 + <exclusion>
2.65 + <artifactId>org.json-osgi</artifactId>
2.66 + <groupId>de.twentyeleven.skysail</groupId>
2.67 + </exclusion>
2.68 + </exclusions>
2.69 </dependency>
2.70 </dependencies>
2.71 </project>
3.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/BrwsrCtxImpl.java Wed Dec 11 08:22:17 2013 +0100
3.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
3.3 @@ -1,166 +0,0 @@
3.4 -/**
3.5 - * Back 2 Browser Bytecode Translator
3.6 - * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
3.7 - *
3.8 - * This program is free software: you can redistribute it and/or modify
3.9 - * it under the terms of the GNU General Public License as published by
3.10 - * the Free Software Foundation, version 2 of the License.
3.11 - *
3.12 - * This program is distributed in the hope that it will be useful,
3.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
3.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3.15 - * GNU General Public License for more details.
3.16 - *
3.17 - * You should have received a copy of the GNU General Public License
3.18 - * along with this program. Look for COPYING file in the top folder.
3.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
3.20 - */
3.21 -package org.apidesign.bck2brwsr.ko2brwsr;
3.22 -
3.23 -import java.io.ByteArrayOutputStream;
3.24 -import java.io.IOException;
3.25 -import java.io.InputStream;
3.26 -import java.io.InputStreamReader;
3.27 -import org.apidesign.html.json.spi.FunctionBinding;
3.28 -import org.apidesign.html.json.spi.JSONCall;
3.29 -import org.apidesign.html.json.spi.PropertyBinding;
3.30 -import org.apidesign.html.json.spi.Technology;
3.31 -import org.apidesign.html.json.spi.Transfer;
3.32 -import org.apidesign.html.json.spi.WSTransfer;
3.33 -
3.34 -/**
3.35 - *
3.36 - * @author Jaroslav Tulach <jtulach@netbeans.org>
3.37 - */
3.38 -final class BrwsrCtxImpl implements Technology<Object>, Transfer, WSTransfer<LoadWS> {
3.39 - private BrwsrCtxImpl() {}
3.40 -
3.41 - public static final BrwsrCtxImpl DEFAULT = new BrwsrCtxImpl();
3.42 -
3.43 - @Override
3.44 - public void extract(Object obj, String[] props, Object[] values) {
3.45 - ConvertTypes.extractJSON(obj, props, values);
3.46 - }
3.47 -
3.48 - @Override
3.49 - public void loadJSON(final JSONCall call) {
3.50 - class R implements Runnable {
3.51 - final boolean success;
3.52 -
3.53 - public R(boolean success) {
3.54 - this.success = success;
3.55 - }
3.56 -
3.57 - Object[] arr = { null };
3.58 - @Override
3.59 - public void run() {
3.60 - if (success) {
3.61 - call.notifySuccess(arr[0]);
3.62 - } else {
3.63 - Throwable t;
3.64 - if (arr[0] instanceof Throwable) {
3.65 - t = (Throwable) arr[0];
3.66 - } else {
3.67 - if (arr[0] == null) {
3.68 - t = new IOException();
3.69 - } else {
3.70 - t = new IOException(arr[0].toString());
3.71 - }
3.72 - }
3.73 - call.notifyError(t);
3.74 - }
3.75 - }
3.76 - }
3.77 - R success = new R(true);
3.78 - R failure = new R(false);
3.79 - if (call.isJSONP()) {
3.80 - String me = ConvertTypes.createJSONP(success.arr, success);
3.81 - ConvertTypes.loadJSONP(call.composeURL(me), me);
3.82 - } else {
3.83 - String data = null;
3.84 - if (call.isDoOutput()) {
3.85 - try {
3.86 - ByteArrayOutputStream bos = new ByteArrayOutputStream();
3.87 - call.writeData(bos);
3.88 - data = new String(bos.toByteArray(), "UTF-8");
3.89 - } catch (IOException ex) {
3.90 - call.notifyError(ex);
3.91 - }
3.92 - }
3.93 - ConvertTypes.loadJSON(call.composeURL(null), success.arr, success, failure, call.getMethod(), data);
3.94 - }
3.95 - }
3.96 -
3.97 - @Override
3.98 - public Object wrapModel(Object model) {
3.99 - return model;
3.100 - }
3.101 -
3.102 - @Override
3.103 - public void bind(PropertyBinding b, Object model, Object data) {
3.104 - Knockout.bind(data, b, b.getPropertyName(),
3.105 - "getValue__Ljava_lang_Object_2",
3.106 - b.isReadOnly() ? null : "setValue__VLjava_lang_Object_2",
3.107 - false, false
3.108 - );
3.109 - }
3.110 -
3.111 - @Override
3.112 - public void valueHasMutated(Object data, String propertyName) {
3.113 - Knockout.valueHasMutated(data, propertyName);
3.114 - }
3.115 -
3.116 - @Override
3.117 - public void expose(FunctionBinding fb, Object model, Object d) {
3.118 - Knockout.expose(d, fb, fb.getFunctionName(), "call__VLjava_lang_Object_2Ljava_lang_Object_2");
3.119 - }
3.120 -
3.121 - @Override
3.122 - public void applyBindings(Object data) {
3.123 - Knockout.applyBindings(data);
3.124 - }
3.125 -
3.126 - @Override
3.127 - public Object wrapArray(Object[] arr) {
3.128 - return arr;
3.129 - }
3.130 -
3.131 - @Override
3.132 - public <M> M toModel(Class<M> modelClass, Object data) {
3.133 - return modelClass.cast(data);
3.134 - }
3.135 -
3.136 - @Override
3.137 - public Object toJSON(InputStream is) throws IOException {
3.138 - StringBuilder sb = new StringBuilder();
3.139 - InputStreamReader r = new InputStreamReader(is);
3.140 - for (;;) {
3.141 - int ch = r.read();
3.142 - if (ch == -1) {
3.143 - break;
3.144 - }
3.145 - sb.append((char)ch);
3.146 - }
3.147 - return ConvertTypes.parse(sb.toString());
3.148 - }
3.149 -
3.150 - @Override
3.151 - public void runSafe(Runnable r) {
3.152 - r.run();
3.153 - }
3.154 -
3.155 - @Override
3.156 - public LoadWS open(String url, JSONCall callback) {
3.157 - return new LoadWS(callback, url);
3.158 - }
3.159 -
3.160 - @Override
3.161 - public void send(LoadWS socket, JSONCall data) {
3.162 - socket.send(data);
3.163 - }
3.164 -
3.165 - @Override
3.166 - public void close(LoadWS socket) {
3.167 - socket.close();
3.168 - }
3.169 -}
4.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/BrwsrCtxPrvdr.java Wed Dec 11 08:22:17 2013 +0100
4.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
4.3 @@ -1,53 +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 org.apidesign.bck2brwsr.core.JavaScriptBody;
4.24 -import org.apidesign.html.context.spi.Contexts;
4.25 -import org.apidesign.html.json.spi.Technology;
4.26 -import org.apidesign.html.json.spi.Transfer;
4.27 -import org.apidesign.html.json.spi.WSTransfer;
4.28 -import org.openide.util.lookup.ServiceProvider;
4.29 -
4.30 -/** This is an implementation package - just
4.31 - * include its JAR on classpath and use official {@link Context} API
4.32 - * to access the functionality.
4.33 - * <p>
4.34 - * Provides binding between models and <a href="http://bck2brwsr.apidesign.org">
4.35 - * Bck2Brwsr</a> VM.
4.36 - * Registers {@link ContextProvider}, so {@link ServiceLoader} can find it.
4.37 - *
4.38 - * @author Jaroslav Tulach <jtulach@netbeans.org>
4.39 - */
4.40 -@ServiceProvider(service = Contexts.Provider.class)
4.41 -public final class BrwsrCtxPrvdr implements Contexts.Provider {
4.42 -
4.43 - @Override
4.44 - public void fillContext(Contexts.Builder context, Class<?> requestor) {
4.45 - if (bck2BrwsrVM()) {
4.46 - context.register(Technology.class, BrwsrCtxImpl.DEFAULT, 50).
4.47 - register(Transfer.class, BrwsrCtxImpl.DEFAULT, 50).
4.48 - register(WSTransfer.class, BrwsrCtxImpl.DEFAULT, 50);
4.49 - }
4.50 - }
4.51 -
4.52 - @JavaScriptBody(args = { }, body = "return true;")
4.53 - private static boolean bck2BrwsrVM() {
4.54 - return false;
4.55 - }
4.56 -}
5.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/ConvertTypes.java Wed Dec 11 08:22:17 2013 +0100
5.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
5.3 @@ -1,157 +0,0 @@
5.4 -/**
5.5 - * Back 2 Browser Bytecode Translator
5.6 - * Copyright (C) 2012 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.
5.16 - *
5.17 - * You should have received a copy of the GNU General Public License
5.18 - * along with this program. Look for COPYING file in the top folder.
5.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
5.20 - */
5.21 -package org.apidesign.bck2brwsr.ko2brwsr;
5.22 -
5.23 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
5.24 -
5.25 -/**
5.26 - *
5.27 - * @author Jaroslav Tulach <jtulach@netbeans.org>
5.28 - */
5.29 -final class ConvertTypes {
5.30 - ConvertTypes() {
5.31 - }
5.32 -
5.33 - public static String toString(Object object, String property) {
5.34 - Object ret = getProperty(object, property);
5.35 - return ret == null ? null : ret.toString();
5.36 - }
5.37 -
5.38 - public static double toDouble(Object object, String property) {
5.39 - Object ret = getProperty(object, property);
5.40 - return ret instanceof Number ? ((Number)ret).doubleValue() : Double.NaN;
5.41 - }
5.42 -
5.43 - public static int toInt(Object object, String property) {
5.44 - Object ret = getProperty(object, property);
5.45 - return ret instanceof Number ? ((Number)ret).intValue() : Integer.MIN_VALUE;
5.46 - }
5.47 -
5.48 - public static <T> T toModel(Class<T> modelClass, Object object, String property) {
5.49 - Object ret = getProperty(object, property);
5.50 - if (ret == null || modelClass.isInstance(ret)) {
5.51 - return modelClass.cast(ret);
5.52 - }
5.53 - throw new IllegalStateException("Value " + ret + " is not of type " + modelClass);
5.54 - }
5.55 -
5.56 - public static String toJSON(Object value) {
5.57 - if (value == null) {
5.58 - return "null";
5.59 - }
5.60 - if (value instanceof Enum) {
5.61 - value = value.toString();
5.62 - }
5.63 - if (value instanceof String) {
5.64 - return '"' +
5.65 - ((String)value).
5.66 - replace("\"", "\\\"").
5.67 - replace("\n", "\\n").
5.68 - replace("\r", "\\r").
5.69 - replace("\t", "\\t")
5.70 - + '"';
5.71 - }
5.72 - return value.toString();
5.73 - }
5.74 -
5.75 - @JavaScriptBody(args = { "object", "property" },
5.76 - body =
5.77 - "if (property === null) return object;\n"
5.78 - + "if (object === null) return null;\n"
5.79 - + "var p = object[property]; return p ? p : null;"
5.80 - )
5.81 - private static Object getProperty(Object object, String property) {
5.82 - return null;
5.83 - }
5.84 -
5.85 - public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
5.86 - int h = whenDone.hashCode();
5.87 - String name;
5.88 - for (;;) {
5.89 - name = "jsonp" + Integer.toHexString(h);
5.90 - if (defineIfUnused(name, jsonResult, whenDone)) {
5.91 - return name;
5.92 - }
5.93 - h++;
5.94 - }
5.95 - }
5.96 -
5.97 - @JavaScriptBody(args = { "name", "arr", "run" }, body =
5.98 - "if (window[name]) return false;\n "
5.99 - + "window[name] = function(data) {\n "
5.100 - + " delete window[name];\n"
5.101 - + " var el = window.document.getElementById(name);\n"
5.102 - + " el.parentNode.removeChild(el);\n"
5.103 - + " arr[0] = data;\n"
5.104 - + " run.run__V();\n"
5.105 - + "};\n"
5.106 - + "return true;\n"
5.107 - )
5.108 - private static boolean defineIfUnused(String name, Object[] arr, Runnable run) {
5.109 - return true;
5.110 - }
5.111 -
5.112 - @JavaScriptBody(args = { "s" }, body = "return eval('(' + s + ')');")
5.113 - static Object parse(String s) {
5.114 - return s;
5.115 - }
5.116 -
5.117 - @JavaScriptBody(args = { "url", "arr", "callback", "onError", "method", "data" }, body = ""
5.118 - + "var request = new XMLHttpRequest();\n"
5.119 - + "if (!method) method = 'GET';\n"
5.120 - + "request.open(method, url, true);\n"
5.121 - + "request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');\n"
5.122 - + "request.onreadystatechange = function() {\n"
5.123 - + " if (this.readyState!==4) return;\n"
5.124 - + " try {\n"
5.125 - + " arr[0] = eval('(' + this.response + ')');\n"
5.126 - + " } catch (error) {;\n"
5.127 - + " arr[0] = this.response;\n"
5.128 - + " }\n"
5.129 - + " callback.run__V();\n"
5.130 - + "};\n"
5.131 - + "request.onerror = function (e) {\n"
5.132 - + " arr[0] = e; onError.run__V();\n"
5.133 - + "}\n"
5.134 - + "if (data) request.send(data);"
5.135 - + "else request.send();"
5.136 - )
5.137 - static void loadJSON(
5.138 - String url, Object[] jsonResult, Runnable whenDone, Runnable whenErr, String method, String data
5.139 - ) {
5.140 - }
5.141 -
5.142 - @JavaScriptBody(args = { "url", "jsonp" }, body =
5.143 - "var scrpt = window.document.createElement('script');\n "
5.144 - + "scrpt.setAttribute('src', url);\n "
5.145 - + "scrpt.setAttribute('id', jsonp);\n "
5.146 - + "scrpt.setAttribute('type', 'text/javascript');\n "
5.147 - + "var body = document.getElementsByTagName('body')[0];\n "
5.148 - + "body.appendChild(scrpt);\n"
5.149 - )
5.150 - static void loadJSONP(String url, String jsonp) {
5.151 -
5.152 - }
5.153 -
5.154 - public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
5.155 - for (int i = 0; i < props.length; i++) {
5.156 - values[i] = getProperty(jsonObject, props[i]);
5.157 - }
5.158 - }
5.159 -
5.160 -}
6.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/Knockout.java Wed Dec 11 08:22:17 2013 +0100
6.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
6.3 @@ -1,131 +0,0 @@
6.4 -/**
6.5 - * Back 2 Browser Bytecode Translator
6.6 - * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
6.7 - *
6.8 - * This program is free software: you can redistribute it and/or modify
6.9 - * it under the terms of the GNU General Public License as published by
6.10 - * the Free Software Foundation, version 2 of the License.
6.11 - *
6.12 - * This program is distributed in the hope that it will be useful,
6.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
6.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6.15 - * GNU General Public License for more details.
6.16 - *
6.17 - * You should have received a copy of the GNU General Public License
6.18 - * along with this program. Look for COPYING file in the top folder.
6.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
6.20 - */
6.21 -package org.apidesign.bck2brwsr.ko2brwsr;
6.22 -
6.23 -import java.lang.reflect.Method;
6.24 -import java.util.List;
6.25 -import org.apidesign.bck2brwsr.core.ExtraJavaScript;
6.26 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
6.27 -
6.28 -/** Provides binding between models and bck2brwsr VM.
6.29 - *
6.30 - * @author Jaroslav Tulach <jtulach@netbeans.org>
6.31 - */
6.32 -@ExtraJavaScript(resource = "/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js")
6.33 -final class Knockout {
6.34 - /** used by tests */
6.35 - static Knockout next;
6.36 - private final Object model;
6.37 -
6.38 - Knockout(Object model) {
6.39 - this.model = model == null ? this : model;
6.40 - }
6.41 -
6.42 - public static <M> Knockout applyBindings(
6.43 - Object model, String[] propsGettersAndSetters,
6.44 - String[] methodsAndSignatures
6.45 - ) {
6.46 - applyImpl(propsGettersAndSetters, model.getClass(), model, model, methodsAndSignatures);
6.47 - return new Knockout(model);
6.48 - }
6.49 - public static <M> Knockout applyBindings(
6.50 - Class<M> modelClass, M model, String[] propsGettersAndSetters,
6.51 - String[] methodsAndSignatures
6.52 - ) {
6.53 - Knockout bindings = next;
6.54 - next = null;
6.55 - if (bindings == null) {
6.56 - bindings = new Knockout(null);
6.57 - }
6.58 - applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
6.59 - applyBindings(bindings);
6.60 - return bindings;
6.61 - }
6.62 -
6.63 - public void valueHasMutated(String prop) {
6.64 - valueHasMutated(model, prop);
6.65 - }
6.66 - @JavaScriptBody(args = { "self", "prop" }, body =
6.67 - "var p = self[prop]; if (p) p.valueHasMutated();"
6.68 - )
6.69 - public static void valueHasMutated(Object self, String prop) {
6.70 - }
6.71 -
6.72 -
6.73 - @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
6.74 - public static void triggerEvent(String id, String ev) {
6.75 - }
6.76 -
6.77 - @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
6.78 - "var bnd = {\n"
6.79 - + " 'read': function() {\n"
6.80 - + " var v = model[getter]();\n"
6.81 - + " if (array) v = v.koArray(); else if (v !== null) v = v.valueOf();\n"
6.82 - + " return v;\n"
6.83 - + " },\n"
6.84 - + " 'owner': bindings\n"
6.85 - + "};\n"
6.86 - + "if (setter != null) {\n"
6.87 - + " bnd['write'] = function(val) {\n"
6.88 - + " var v = val === null ? null : val.valueOf();"
6.89 - + " model[setter](v);\n"
6.90 - + " };\n"
6.91 - + "}\n"
6.92 - + "bindings[prop] = ko['computed'](bnd);"
6.93 - )
6.94 - static void bind(
6.95 - Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
6.96 - ) {
6.97 - }
6.98 -
6.99 - @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
6.100 - "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
6.101 - )
6.102 - static void expose(
6.103 - Object bindings, Object model, String prop, String sig
6.104 - ) {
6.105 - }
6.106 -
6.107 - @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
6.108 - static void applyBindings(Object bindings) {}
6.109 -
6.110 - private static void applyImpl(
6.111 - String[] propsGettersAndSetters,
6.112 - Class<?> modelClass,
6.113 - Object bindings,
6.114 - Object model,
6.115 - String[] methodsAndSignatures
6.116 - ) throws IllegalStateException, SecurityException {
6.117 - for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
6.118 - try {
6.119 - Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
6.120 - bind(bindings, model, propsGettersAndSetters[i],
6.121 - propsGettersAndSetters[i + 1],
6.122 - propsGettersAndSetters[i + 2],
6.123 - getter.getReturnType().isPrimitive(),
6.124 - List.class.isAssignableFrom(getter.getReturnType()));
6.125 - } catch (NoSuchMethodException ex) {
6.126 - throw new IllegalStateException(ex.getMessage());
6.127 - }
6.128 - }
6.129 - for (int i = 0; i < methodsAndSignatures.length; i += 2) {
6.130 - expose(
6.131 - bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
6.132 - }
6.133 - }
6.134 -}
7.1 --- a/ko/bck2brwsr/src/main/java/org/apidesign/bck2brwsr/ko2brwsr/LoadWS.java Wed Dec 11 08:22:17 2013 +0100
7.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
7.3 @@ -1,126 +0,0 @@
7.4 -/**
7.5 - * Back 2 Browser Bytecode Translator
7.6 - * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
7.7 - *
7.8 - * This program is free software: you can redistribute it and/or modify
7.9 - * it under the terms of the GNU General Public License as published by
7.10 - * the Free Software Foundation, version 2 of the License.
7.11 - *
7.12 - * This program is distributed in the hope that it will be useful,
7.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
7.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7.15 - * GNU General Public License for more details.
7.16 - *
7.17 - * You should have received a copy of the GNU General Public License
7.18 - * along with this program. Look for COPYING file in the top folder.
7.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
7.20 - */
7.21 -package org.apidesign.bck2brwsr.ko2brwsr;
7.22 -
7.23 -import net.java.html.js.JavaScriptBody;
7.24 -import org.apidesign.html.json.spi.JSONCall;
7.25 -
7.26 -/** Communication with WebSockets for WebView 1.8.
7.27 - *
7.28 - * @author Jaroslav Tulach <jtulach@netbeans.org>
7.29 - */
7.30 -final class LoadWS {
7.31 - private static final boolean SUPPORTED = isWebSocket();
7.32 - private final Object ws;
7.33 - private final JSONCall call;
7.34 - LoadWS(JSONCall first, String url) {
7.35 - call = first;
7.36 - ws = initWebSocket(this, url);
7.37 - if (ws == null) {
7.38 - first.notifyError(new IllegalArgumentException("Wrong URL: " + url));
7.39 - }
7.40 - }
7.41 -
7.42 - static boolean isSupported() {
7.43 - return SUPPORTED;
7.44 - }
7.45 -
7.46 - void send(JSONCall call) {
7.47 - push(call);
7.48 - }
7.49 -
7.50 - private synchronized void push(JSONCall call) {
7.51 - send(ws, call.getMessage());
7.52 - }
7.53 -
7.54 - void onOpen(Object ev) {
7.55 - if (!call.isDoOutput()) {
7.56 - call.notifySuccess(null);
7.57 - }
7.58 - }
7.59 -
7.60 -
7.61 - @JavaScriptBody(args = { "data" }, body = "try {\n"
7.62 - + " return eval('(' + data + ')');\n"
7.63 - + " } catch (error) {;\n"
7.64 - + " return data;\n"
7.65 - + " }\n"
7.66 - )
7.67 - private static native Object toJSON(String data);
7.68 -
7.69 - void onMessage(Object ev, String data) {
7.70 - Object json = toJSON(data);
7.71 - call.notifySuccess(json);
7.72 - }
7.73 -
7.74 - void onError(Object ev) {
7.75 - call.notifyError(new Exception(ev.toString()));
7.76 - }
7.77 -
7.78 - void onClose(boolean wasClean, int code, String reason) {
7.79 - call.notifyError(null);
7.80 - }
7.81 -
7.82 - @JavaScriptBody(args = {}, body = "if (window.WebSocket) return true; else return false;")
7.83 - private static boolean isWebSocket() {
7.84 - return false;
7.85 - }
7.86 -
7.87 - @JavaScriptBody(args = { "back", "url" }, javacall = true, body = ""
7.88 - + "if (window.WebSocket) {\n"
7.89 - + " try {\n"
7.90 - + " var ws = new window.WebSocket(url);\n"
7.91 - + " ws.onopen = function(ev) {\n"
7.92 - + " back.@org.apidesign.bck2brwsr.ko2brwsr.LoadWS::onOpen(Ljava/lang/Object;)(ev);\n"
7.93 - + " };\n"
7.94 - + " ws.onmessage = function(ev) {\n"
7.95 - + " back.@org.apidesign.bck2brwsr.ko2brwsr.LoadWS::onMessage(Ljava/lang/Object;Ljava/lang/String;)(ev, ev.data);\n"
7.96 - + " };\n"
7.97 - + " ws.onerror = function(ev) {\n"
7.98 - + " back.@org.apidesign.bck2brwsr.ko2brwsr.LoadWS::onError(Ljava/lang/Object;)(ev);\n"
7.99 - + " };\n"
7.100 - + " ws.onclose = function(ev) {\n"
7.101 - + " back.@org.apidesign.bck2brwsr.ko2brwsr.LoadWS::onClose(ZILjava/lang/String;)(ev.wasClean, ev.code, ev.reason);\n"
7.102 - + " };\n"
7.103 - + " return ws;\n"
7.104 - + " } catch (ex) {\n"
7.105 - + " return null;\n"
7.106 - + " }\n"
7.107 - + "} else {\n"
7.108 - + " return null;\n"
7.109 - + "}\n"
7.110 - )
7.111 - private static Object initWebSocket(Object back, String url) {
7.112 - return null;
7.113 - }
7.114 -
7.115 -
7.116 - @JavaScriptBody(args = { "ws", "msg" }, body = ""
7.117 - + "ws.send(msg);"
7.118 - )
7.119 - private void send(Object ws, String msg) {
7.120 - }
7.121 -
7.122 - @JavaScriptBody(args = { "ws" }, body = "ws.close();")
7.123 - private static void close(Object ws) {
7.124 - }
7.125 -
7.126 - void close() {
7.127 - close(ws);
7.128 - }
7.129 -}
8.1 --- a/ko/bck2brwsr/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js Wed Dec 11 08:22:17 2013 +0100
8.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
8.3 @@ -1,3614 +0,0 @@
8.4 -/*
8.5 - * HTML via Java(tm) Language Bindings
8.6 - * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
8.7 - *
8.8 - * This program is free software: you can redistribute it and/or modify
8.9 - * it under the terms of the GNU General Public License as published by
8.10 - * the Free Software Foundation, version 2 of the License.
8.11 - *
8.12 - * This program is distributed in the hope that it will be useful,
8.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
8.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8.15 - * GNU General Public License for more details. apidesign.org
8.16 - * designates this particular file as subject to the
8.17 - * "Classpath" exception as provided by apidesign.org
8.18 - * in the License file that accompanied this code.
8.19 - *
8.20 - * You should have received a copy of the GNU General Public License
8.21 - * along with this program. Look for COPYING file in the top folder.
8.22 - * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
8.23 - */
8.24 -// Knockout JavaScript library v2.2.1
8.25 -// (c) Steven Sanderson - http://knockoutjs.com/
8.26 -// License: MIT (http://www.opensource.org/licenses/mit-license.php)
8.27 -
8.28 -(function(){
8.29 -var DEBUG=true;
8.30 -(function(window,document,navigator,jQuery,undefined){
8.31 -!function(factory) {
8.32 - // Support three module loading scenarios
8.33 - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
8.34 - // [1] CommonJS/Node.js
8.35 - var target = module['exports'] || exports; // module.exports is for Node.js
8.36 - factory(target);
8.37 - } else if (typeof define === 'function' && define['amd']) {
8.38 - // [2] AMD anonymous module
8.39 - define(['exports'], factory);
8.40 - } else {
8.41 - // [3] No module loader (plain <script> tag) - put directly in global namespace
8.42 - factory(window['ko'] = {});
8.43 - }
8.44 -}(function(koExports){
8.45 -// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
8.46 -// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
8.47 -var ko = typeof koExports !== 'undefined' ? koExports : {};
8.48 -// Google Closure Compiler helpers (used only to make the minified file smaller)
8.49 -ko.exportSymbol = function(koPath, object) {
8.50 - var tokens = koPath.split(".");
8.51 -
8.52 - // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
8.53 - // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
8.54 - var target = ko;
8.55 -
8.56 - for (var i = 0; i < tokens.length - 1; i++)
8.57 - target = target[tokens[i]];
8.58 - target[tokens[tokens.length - 1]] = object;
8.59 -};
8.60 -ko.exportProperty = function(owner, publicName, object) {
8.61 - owner[publicName] = object;
8.62 -};
8.63 -ko.version = "2.2.1";
8.64 -
8.65 -ko.exportSymbol('version', ko.version);
8.66 -ko.utils = new (function () {
8.67 - var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
8.68 -
8.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)
8.70 - var knownEvents = {}, knownEventTypesByEventName = {};
8.71 - var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
8.72 - knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
8.73 - knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
8.74 - for (var eventType in knownEvents) {
8.75 - var knownEventsForType = knownEvents[eventType];
8.76 - if (knownEventsForType.length) {
8.77 - for (var i = 0, j = knownEventsForType.length; i < j; i++)
8.78 - knownEventTypesByEventName[knownEventsForType[i]] = eventType;
8.79 - }
8.80 - }
8.81 - var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
8.82 -
8.83 - // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
8.84 - // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
8.85 - // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
8.86 - // If there is a future need to detect specific versions of IE10+, we will amend this.
8.87 - var ieVersion = (function() {
8.88 - var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
8.89 -
8.90 - // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
8.91 - while (
8.92 - div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
8.93 - iElems[0]
8.94 - );
8.95 - return version > 4 ? version : undefined;
8.96 - }());
8.97 - var isIe6 = ieVersion === 6,
8.98 - isIe7 = ieVersion === 7;
8.99 -
8.100 - function isClickOnCheckableElement(element, eventType) {
8.101 - if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
8.102 - if (eventType.toLowerCase() != "click") return false;
8.103 - var inputType = element.type;
8.104 - return (inputType == "checkbox") || (inputType == "radio");
8.105 - }
8.106 -
8.107 - return {
8.108 - fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
8.109 -
8.110 - arrayForEach: function (array, action) {
8.111 - for (var i = 0, j = array.length; i < j; i++)
8.112 - action(array[i]);
8.113 - },
8.114 -
8.115 - arrayIndexOf: function (array, item) {
8.116 - if (typeof Array.prototype.indexOf == "function")
8.117 - return Array.prototype.indexOf.call(array, item);
8.118 - for (var i = 0, j = array.length; i < j; i++)
8.119 - if (array[i] === item)
8.120 - return i;
8.121 - return -1;
8.122 - },
8.123 -
8.124 - arrayFirst: function (array, predicate, predicateOwner) {
8.125 - for (var i = 0, j = array.length; i < j; i++)
8.126 - if (predicate.call(predicateOwner, array[i]))
8.127 - return array[i];
8.128 - return null;
8.129 - },
8.130 -
8.131 - arrayRemoveItem: function (array, itemToRemove) {
8.132 - var index = ko.utils.arrayIndexOf(array, itemToRemove);
8.133 - if (index >= 0)
8.134 - array.splice(index, 1);
8.135 - },
8.136 -
8.137 - arrayGetDistinctValues: function (array) {
8.138 - array = array || [];
8.139 - var result = [];
8.140 - for (var i = 0, j = array.length; i < j; i++) {
8.141 - if (ko.utils.arrayIndexOf(result, array[i]) < 0)
8.142 - result.push(array[i]);
8.143 - }
8.144 - return result;
8.145 - },
8.146 -
8.147 - arrayMap: function (array, mapping) {
8.148 - array = array || [];
8.149 - var result = [];
8.150 - for (var i = 0, j = array.length; i < j; i++)
8.151 - result.push(mapping(array[i]));
8.152 - return result;
8.153 - },
8.154 -
8.155 - arrayFilter: function (array, predicate) {
8.156 - array = array || [];
8.157 - var result = [];
8.158 - for (var i = 0, j = array.length; i < j; i++)
8.159 - if (predicate(array[i]))
8.160 - result.push(array[i]);
8.161 - return result;
8.162 - },
8.163 -
8.164 - arrayPushAll: function (array, valuesToPush) {
8.165 - if (valuesToPush instanceof Array)
8.166 - array.push.apply(array, valuesToPush);
8.167 - else
8.168 - for (var i = 0, j = valuesToPush.length; i < j; i++)
8.169 - array.push(valuesToPush[i]);
8.170 - return array;
8.171 - },
8.172 -
8.173 - extend: function (target, source) {
8.174 - if (source) {
8.175 - for(var prop in source) {
8.176 - if(source.hasOwnProperty(prop)) {
8.177 - target[prop] = source[prop];
8.178 - }
8.179 - }
8.180 - }
8.181 - return target;
8.182 - },
8.183 -
8.184 - emptyDomNode: function (domNode) {
8.185 - while (domNode.firstChild) {
8.186 - ko.removeNode(domNode.firstChild);
8.187 - }
8.188 - },
8.189 -
8.190 - moveCleanedNodesToContainerElement: function(nodes) {
8.191 - // Ensure it's a real array, as we're about to reparent the nodes and
8.192 - // we don't want the underlying collection to change while we're doing that.
8.193 - var nodesArray = ko.utils.makeArray(nodes);
8.194 -
8.195 - var container = document.createElement('div');
8.196 - for (var i = 0, j = nodesArray.length; i < j; i++) {
8.197 - container.appendChild(ko.cleanNode(nodesArray[i]));
8.198 - }
8.199 - return container;
8.200 - },
8.201 -
8.202 - cloneNodes: function (nodesArray, shouldCleanNodes) {
8.203 - for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
8.204 - var clonedNode = nodesArray[i].cloneNode(true);
8.205 - newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
8.206 - }
8.207 - return newNodesArray;
8.208 - },
8.209 -
8.210 - setDomNodeChildren: function (domNode, childNodes) {
8.211 - ko.utils.emptyDomNode(domNode);
8.212 - if (childNodes) {
8.213 - for (var i = 0, j = childNodes.length; i < j; i++)
8.214 - domNode.appendChild(childNodes[i]);
8.215 - }
8.216 - },
8.217 -
8.218 - replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
8.219 - var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
8.220 - if (nodesToReplaceArray.length > 0) {
8.221 - var insertionPoint = nodesToReplaceArray[0];
8.222 - var parent = insertionPoint.parentNode;
8.223 - for (var i = 0, j = newNodesArray.length; i < j; i++)
8.224 - parent.insertBefore(newNodesArray[i], insertionPoint);
8.225 - for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
8.226 - ko.removeNode(nodesToReplaceArray[i]);
8.227 - }
8.228 - }
8.229 - },
8.230 -
8.231 - setOptionNodeSelectionState: function (optionNode, isSelected) {
8.232 - // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
8.233 - if (ieVersion < 7)
8.234 - optionNode.setAttribute("selected", isSelected);
8.235 - else
8.236 - optionNode.selected = isSelected;
8.237 - },
8.238 -
8.239 - stringTrim: function (string) {
8.240 - return (string || "").replace(stringTrimRegex, "");
8.241 - },
8.242 -
8.243 - stringTokenize: function (string, delimiter) {
8.244 - var result = [];
8.245 - var tokens = (string || "").split(delimiter);
8.246 - for (var i = 0, j = tokens.length; i < j; i++) {
8.247 - var trimmed = ko.utils.stringTrim(tokens[i]);
8.248 - if (trimmed !== "")
8.249 - result.push(trimmed);
8.250 - }
8.251 - return result;
8.252 - },
8.253 -
8.254 - stringStartsWith: function (string, startsWith) {
8.255 - string = string || "";
8.256 - if (startsWith.length > string.length)
8.257 - return false;
8.258 - return string.substring(0, startsWith.length) === startsWith;
8.259 - },
8.260 -
8.261 - domNodeIsContainedBy: function (node, containedByNode) {
8.262 - if (containedByNode.compareDocumentPosition)
8.263 - return (containedByNode.compareDocumentPosition(node) & 16) == 16;
8.264 - while (node != null) {
8.265 - if (node == containedByNode)
8.266 - return true;
8.267 - node = node.parentNode;
8.268 - }
8.269 - return false;
8.270 - },
8.271 -
8.272 - domNodeIsAttachedToDocument: function (node) {
8.273 - return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
8.274 - },
8.275 -
8.276 - tagNameLower: function(element) {
8.277 - // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
8.278 - // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
8.279 - // we don't need to do the .toLowerCase() as it will always be lower case anyway.
8.280 - return element && element.tagName && element.tagName.toLowerCase();
8.281 - },
8.282 -
8.283 - registerEventHandler: function (element, eventType, handler) {
8.284 - var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
8.285 - if (!mustUseAttachEvent && typeof jQuery != "undefined") {
8.286 - if (isClickOnCheckableElement(element, eventType)) {
8.287 - // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
8.288 - // it toggles the element checked state *after* the click event handlers run, whereas native
8.289 - // click events toggle the checked state *before* the event handler.
8.290 - // Fix this by intecepting the handler and applying the correct checkedness before it runs.
8.291 - var originalHandler = handler;
8.292 - handler = function(event, eventData) {
8.293 - var jQuerySuppliedCheckedState = this.checked;
8.294 - if (eventData)
8.295 - this.checked = eventData.checkedStateBeforeEvent !== true;
8.296 - originalHandler.call(this, event);
8.297 - this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
8.298 - };
8.299 - }
8.300 - jQuery(element)['bind'](eventType, handler);
8.301 - } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
8.302 - element.addEventListener(eventType, handler, false);
8.303 - else if (typeof element.attachEvent != "undefined")
8.304 - element.attachEvent("on" + eventType, function (event) {
8.305 - handler.call(element, event);
8.306 - });
8.307 - else
8.308 - throw new Error("Browser doesn't support addEventListener or attachEvent");
8.309 - },
8.310 -
8.311 - triggerEvent: function (element, eventType) {
8.312 - if (!(element && element.nodeType))
8.313 - throw new Error("element must be a DOM node when calling triggerEvent");
8.314 -
8.315 - if (typeof jQuery != "undefined") {
8.316 - var eventData = [];
8.317 - if (isClickOnCheckableElement(element, eventType)) {
8.318 - // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
8.319 - eventData.push({ checkedStateBeforeEvent: element.checked });
8.320 - }
8.321 - jQuery(element)['trigger'](eventType, eventData);
8.322 - } else if (typeof document.createEvent == "function") {
8.323 - if (typeof element.dispatchEvent == "function") {
8.324 - var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
8.325 - var event = document.createEvent(eventCategory);
8.326 - event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
8.327 - element.dispatchEvent(event);
8.328 - }
8.329 - else
8.330 - throw new Error("The supplied element doesn't support dispatchEvent");
8.331 - } else if (typeof element.fireEvent != "undefined") {
8.332 - // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
8.333 - // so to make it consistent, we'll do it manually here
8.334 - if (isClickOnCheckableElement(element, eventType))
8.335 - element.checked = element.checked !== true;
8.336 - element.fireEvent("on" + eventType);
8.337 - }
8.338 - else
8.339 - throw new Error("Browser doesn't support triggering events");
8.340 - },
8.341 -
8.342 - unwrapObservable: function (value) {
8.343 - return ko.isObservable(value) ? value() : value;
8.344 - },
8.345 -
8.346 - peekObservable: function (value) {
8.347 - return ko.isObservable(value) ? value.peek() : value;
8.348 - },
8.349 -
8.350 - toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
8.351 - if (classNames) {
8.352 - var cssClassNameRegex = /[\w-]+/g,
8.353 - currentClassNames = node.className.match(cssClassNameRegex) || [];
8.354 - ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
8.355 - var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
8.356 - if (indexOfClass >= 0) {
8.357 - if (!shouldHaveClass)
8.358 - currentClassNames.splice(indexOfClass, 1);
8.359 - } else {
8.360 - if (shouldHaveClass)
8.361 - currentClassNames.push(className);
8.362 - }
8.363 - });
8.364 - node.className = currentClassNames.join(" ");
8.365 - }
8.366 - },
8.367 -
8.368 - setTextContent: function(element, textContent) {
8.369 - var value = ko.utils.unwrapObservable(textContent);
8.370 - if ((value === null) || (value === undefined))
8.371 - value = "";
8.372 -
8.373 - if (element.nodeType === 3) {
8.374 - element.data = value;
8.375 - } else {
8.376 - // We need there to be exactly one child: a text node.
8.377 - // If there are no children, more than one, or if it's not a text node,
8.378 - // we'll clear everything and create a single text node.
8.379 - var innerTextNode = ko.virtualElements.firstChild(element);
8.380 - if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
8.381 - ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
8.382 - } else {
8.383 - innerTextNode.data = value;
8.384 - }
8.385 -
8.386 - ko.utils.forceRefresh(element);
8.387 - }
8.388 - },
8.389 -
8.390 - setElementName: function(element, name) {
8.391 - element.name = name;
8.392 -
8.393 - // Workaround IE 6/7 issue
8.394 - // - https://github.com/SteveSanderson/knockout/issues/197
8.395 - // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
8.396 - if (ieVersion <= 7) {
8.397 - try {
8.398 - element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
8.399 - }
8.400 - catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
8.401 - }
8.402 - },
8.403 -
8.404 - forceRefresh: function(node) {
8.405 - // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
8.406 - if (ieVersion >= 9) {
8.407 - // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
8.408 - var elem = node.nodeType == 1 ? node : node.parentNode;
8.409 - if (elem.style)
8.410 - elem.style.zoom = elem.style.zoom;
8.411 - }
8.412 - },
8.413 -
8.414 - ensureSelectElementIsRenderedCorrectly: function(selectElement) {
8.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.
8.416 - // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
8.417 - if (ieVersion >= 9) {
8.418 - var originalWidth = selectElement.style.width;
8.419 - selectElement.style.width = 0;
8.420 - selectElement.style.width = originalWidth;
8.421 - }
8.422 - },
8.423 -
8.424 - range: function (min, max) {
8.425 - min = ko.utils.unwrapObservable(min);
8.426 - max = ko.utils.unwrapObservable(max);
8.427 - var result = [];
8.428 - for (var i = min; i <= max; i++)
8.429 - result.push(i);
8.430 - return result;
8.431 - },
8.432 -
8.433 - makeArray: function(arrayLikeObject) {
8.434 - var result = [];
8.435 - for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
8.436 - result.push(arrayLikeObject[i]);
8.437 - };
8.438 - return result;
8.439 - },
8.440 -
8.441 - isIe6 : isIe6,
8.442 - isIe7 : isIe7,
8.443 - ieVersion : ieVersion,
8.444 -
8.445 - getFormFields: function(form, fieldName) {
8.446 - var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
8.447 - var isMatchingField = (typeof fieldName == 'string')
8.448 - ? function(field) { return field.name === fieldName }
8.449 - : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
8.450 - var matches = [];
8.451 - for (var i = fields.length - 1; i >= 0; i--) {
8.452 - if (isMatchingField(fields[i]))
8.453 - matches.push(fields[i]);
8.454 - };
8.455 - return matches;
8.456 - },
8.457 -
8.458 - parseJson: function (jsonString) {
8.459 - if (typeof jsonString == "string") {
8.460 - jsonString = ko.utils.stringTrim(jsonString);
8.461 - if (jsonString) {
8.462 - if (window.JSON && window.JSON.parse) // Use native parsing where available
8.463 - return window.JSON.parse(jsonString);
8.464 - return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
8.465 - }
8.466 - }
8.467 - return null;
8.468 - },
8.469 -
8.470 - stringifyJson: function (data, replacer, space) { // replacer and space are optional
8.471 - if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
8.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");
8.473 - return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
8.474 - },
8.475 -
8.476 - postJson: function (urlOrForm, data, options) {
8.477 - options = options || {};
8.478 - var params = options['params'] || {};
8.479 - var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
8.480 - var url = urlOrForm;
8.481 -
8.482 - // If we were given a form, use its 'action' URL and pick out any requested field values
8.483 - if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
8.484 - var originalForm = urlOrForm;
8.485 - url = originalForm.action;
8.486 - for (var i = includeFields.length - 1; i >= 0; i--) {
8.487 - var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
8.488 - for (var j = fields.length - 1; j >= 0; j--)
8.489 - params[fields[j].name] = fields[j].value;
8.490 - }
8.491 - }
8.492 -
8.493 - data = ko.utils.unwrapObservable(data);
8.494 - var form = document.createElement("form");
8.495 - form.style.display = "none";
8.496 - form.action = url;
8.497 - form.method = "post";
8.498 - for (var key in data) {
8.499 - var input = document.createElement("input");
8.500 - input.name = key;
8.501 - input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
8.502 - form.appendChild(input);
8.503 - }
8.504 - for (var key in params) {
8.505 - var input = document.createElement("input");
8.506 - input.name = key;
8.507 - input.value = params[key];
8.508 - form.appendChild(input);
8.509 - }
8.510 - document.body.appendChild(form);
8.511 - options['submitter'] ? options['submitter'](form) : form.submit();
8.512 - setTimeout(function () { form.parentNode.removeChild(form); }, 0);
8.513 - }
8.514 - }
8.515 -})();
8.516 -
8.517 -ko.exportSymbol('utils', ko.utils);
8.518 -ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
8.519 -ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
8.520 -ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
8.521 -ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
8.522 -ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
8.523 -ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
8.524 -ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
8.525 -ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
8.526 -ko.exportSymbol('utils.extend', ko.utils.extend);
8.527 -ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
8.528 -ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
8.529 -ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
8.530 -ko.exportSymbol('utils.postJson', ko.utils.postJson);
8.531 -ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
8.532 -ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
8.533 -ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
8.534 -ko.exportSymbol('utils.range', ko.utils.range);
8.535 -ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
8.536 -ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
8.537 -ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
8.538 -
8.539 -if (!Function.prototype['bind']) {
8.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)
8.541 - // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
8.542 - Function.prototype['bind'] = function (object) {
8.543 - var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
8.544 - return function () {
8.545 - return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
8.546 - };
8.547 - };
8.548 -}
8.549 -
8.550 -ko.utils.domData = new (function () {
8.551 - var uniqueId = 0;
8.552 - var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
8.553 - var dataStore = {};
8.554 - return {
8.555 - get: function (node, key) {
8.556 - var allDataForNode = ko.utils.domData.getAll(node, false);
8.557 - return allDataForNode === undefined ? undefined : allDataForNode[key];
8.558 - },
8.559 - set: function (node, key, value) {
8.560 - if (value === undefined) {
8.561 - // Make sure we don't actually create a new domData key if we are actually deleting a value
8.562 - if (ko.utils.domData.getAll(node, false) === undefined)
8.563 - return;
8.564 - }
8.565 - var allDataForNode = ko.utils.domData.getAll(node, true);
8.566 - allDataForNode[key] = value;
8.567 - },
8.568 - getAll: function (node, createIfNotFound) {
8.569 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
8.570 - var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
8.571 - if (!hasExistingDataStore) {
8.572 - if (!createIfNotFound)
8.573 - return undefined;
8.574 - dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
8.575 - dataStore[dataStoreKey] = {};
8.576 - }
8.577 - return dataStore[dataStoreKey];
8.578 - },
8.579 - clear: function (node) {
8.580 - var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
8.581 - if (dataStoreKey) {
8.582 - delete dataStore[dataStoreKey];
8.583 - node[dataStoreKeyExpandoPropertyName] = null;
8.584 - return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
8.585 - }
8.586 - return false;
8.587 - }
8.588 - }
8.589 -})();
8.590 -
8.591 -ko.exportSymbol('utils.domData', ko.utils.domData);
8.592 -ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
8.593 -
8.594 -ko.utils.domNodeDisposal = new (function () {
8.595 - var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
8.596 - var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
8.597 - var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
8.598 -
8.599 - function getDisposeCallbacksCollection(node, createIfNotFound) {
8.600 - var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
8.601 - if ((allDisposeCallbacks === undefined) && createIfNotFound) {
8.602 - allDisposeCallbacks = [];
8.603 - ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
8.604 - }
8.605 - return allDisposeCallbacks;
8.606 - }
8.607 - function destroyCallbacksCollection(node) {
8.608 - ko.utils.domData.set(node, domDataKey, undefined);
8.609 - }
8.610 -
8.611 - function cleanSingleNode(node) {
8.612 - // Run all the dispose callbacks
8.613 - var callbacks = getDisposeCallbacksCollection(node, false);
8.614 - if (callbacks) {
8.615 - callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
8.616 - for (var i = 0; i < callbacks.length; i++)
8.617 - callbacks[i](node);
8.618 - }
8.619 -
8.620 - // Also erase the DOM data
8.621 - ko.utils.domData.clear(node);
8.622 -
8.623 - // Special support for jQuery here because it's so commonly used.
8.624 - // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
8.625 - // so notify it to tear down any resources associated with the node & descendants here.
8.626 - if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
8.627 - jQuery['cleanData']([node]);
8.628 -
8.629 - // Also clear any immediate-child comment nodes, as these wouldn't have been found by
8.630 - // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
8.631 - if (cleanableNodeTypesWithDescendants[node.nodeType])
8.632 - cleanImmediateCommentTypeChildren(node);
8.633 - }
8.634 -
8.635 - function cleanImmediateCommentTypeChildren(nodeWithChildren) {
8.636 - var child, nextChild = nodeWithChildren.firstChild;
8.637 - while (child = nextChild) {
8.638 - nextChild = child.nextSibling;
8.639 - if (child.nodeType === 8)
8.640 - cleanSingleNode(child);
8.641 - }
8.642 - }
8.643 -
8.644 - return {
8.645 - addDisposeCallback : function(node, callback) {
8.646 - if (typeof callback != "function")
8.647 - throw new Error("Callback must be a function");
8.648 - getDisposeCallbacksCollection(node, true).push(callback);
8.649 - },
8.650 -
8.651 - removeDisposeCallback : function(node, callback) {
8.652 - var callbacksCollection = getDisposeCallbacksCollection(node, false);
8.653 - if (callbacksCollection) {
8.654 - ko.utils.arrayRemoveItem(callbacksCollection, callback);
8.655 - if (callbacksCollection.length == 0)
8.656 - destroyCallbacksCollection(node);
8.657 - }
8.658 - },
8.659 -
8.660 - cleanNode : function(node) {
8.661 - // First clean this node, where applicable
8.662 - if (cleanableNodeTypes[node.nodeType]) {
8.663 - cleanSingleNode(node);
8.664 -
8.665 - // ... then its descendants, where applicable
8.666 - if (cleanableNodeTypesWithDescendants[node.nodeType]) {
8.667 - // Clone the descendants list in case it changes during iteration
8.668 - var descendants = [];
8.669 - ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
8.670 - for (var i = 0, j = descendants.length; i < j; i++)
8.671 - cleanSingleNode(descendants[i]);
8.672 - }
8.673 - }
8.674 - return node;
8.675 - },
8.676 -
8.677 - removeNode : function(node) {
8.678 - ko.cleanNode(node);
8.679 - if (node.parentNode)
8.680 - node.parentNode.removeChild(node);
8.681 - }
8.682 - }
8.683 -})();
8.684 -ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
8.685 -ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
8.686 -ko.exportSymbol('cleanNode', ko.cleanNode);
8.687 -ko.exportSymbol('removeNode', ko.removeNode);
8.688 -ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
8.689 -ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
8.690 -ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
8.691 -(function () {
8.692 - var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
8.693 -
8.694 - function simpleHtmlParse(html) {
8.695 - // Based on jQuery's "clean" function, but only accounting for table-related elements.
8.696 - // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
8.697 -
8.698 - // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
8.699 - // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
8.700 - // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
8.701 - // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
8.702 -
8.703 - // Trim whitespace, otherwise indexOf won't work as expected
8.704 - var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
8.705 -
8.706 - // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
8.707 - var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
8.708 - !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
8.709 - (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
8.710 - /* anything else */ [0, "", ""];
8.711 -
8.712 - // Go to html and back, then peel off extra wrappers
8.713 - // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
8.714 - var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
8.715 - if (typeof window['innerShiv'] == "function") {
8.716 - div.appendChild(window['innerShiv'](markup));
8.717 - } else {
8.718 - div.innerHTML = markup;
8.719 - }
8.720 -
8.721 - // Move to the right depth
8.722 - while (wrap[0]--)
8.723 - div = div.lastChild;
8.724 -
8.725 - return ko.utils.makeArray(div.lastChild.childNodes);
8.726 - }
8.727 -
8.728 - function jQueryHtmlParse(html) {
8.729 - // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
8.730 - if (jQuery['parseHTML']) {
8.731 - return jQuery['parseHTML'](html);
8.732 - } else {
8.733 - // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
8.734 - var elems = jQuery['clean']([html]);
8.735 -
8.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.
8.737 - // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
8.738 - // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
8.739 - if (elems && elems[0]) {
8.740 - // Find the top-most parent element that's a direct child of a document fragment
8.741 - var elem = elems[0];
8.742 - while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
8.743 - elem = elem.parentNode;
8.744 - // ... then detach it
8.745 - if (elem.parentNode)
8.746 - elem.parentNode.removeChild(elem);
8.747 - }
8.748 -
8.749 - return elems;
8.750 - }
8.751 - }
8.752 -
8.753 - ko.utils.parseHtmlFragment = function(html) {
8.754 - return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
8.755 - : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
8.756 - };
8.757 -
8.758 - ko.utils.setHtml = function(node, html) {
8.759 - ko.utils.emptyDomNode(node);
8.760 -
8.761 - // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
8.762 - html = ko.utils.unwrapObservable(html);
8.763 -
8.764 - if ((html !== null) && (html !== undefined)) {
8.765 - if (typeof html != 'string')
8.766 - html = html.toString();
8.767 -
8.768 - // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
8.769 - // for example <tr> elements which are not normally allowed to exist on their own.
8.770 - // If you've referenced jQuery we'll use that rather than duplicating its code.
8.771 - if (typeof jQuery != 'undefined') {
8.772 - jQuery(node)['html'](html);
8.773 - } else {
8.774 - // ... otherwise, use KO's own parsing logic.
8.775 - var parsedNodes = ko.utils.parseHtmlFragment(html);
8.776 - for (var i = 0; i < parsedNodes.length; i++)
8.777 - node.appendChild(parsedNodes[i]);
8.778 - }
8.779 - }
8.780 - };
8.781 -})();
8.782 -
8.783 -ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
8.784 -ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
8.785 -
8.786 -ko.memoization = (function () {
8.787 - var memos = {};
8.788 -
8.789 - function randomMax8HexChars() {
8.790 - return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
8.791 - }
8.792 - function generateRandomId() {
8.793 - return randomMax8HexChars() + randomMax8HexChars();
8.794 - }
8.795 - function findMemoNodes(rootNode, appendToArray) {
8.796 - if (!rootNode)
8.797 - return;
8.798 - if (rootNode.nodeType == 8) {
8.799 - var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
8.800 - if (memoId != null)
8.801 - appendToArray.push({ domNode: rootNode, memoId: memoId });
8.802 - } else if (rootNode.nodeType == 1) {
8.803 - for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
8.804 - findMemoNodes(childNodes[i], appendToArray);
8.805 - }
8.806 - }
8.807 -
8.808 - return {
8.809 - memoize: function (callback) {
8.810 - if (typeof callback != "function")
8.811 - throw new Error("You can only pass a function to ko.memoization.memoize()");
8.812 - var memoId = generateRandomId();
8.813 - memos[memoId] = callback;
8.814 - return "<!--[ko_memo:" + memoId + "]-->";
8.815 - },
8.816 -
8.817 - unmemoize: function (memoId, callbackParams) {
8.818 - var callback = memos[memoId];
8.819 - if (callback === undefined)
8.820 - throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
8.821 - try {
8.822 - callback.apply(null, callbackParams || []);
8.823 - return true;
8.824 - }
8.825 - finally { delete memos[memoId]; }
8.826 - },
8.827 -
8.828 - unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
8.829 - var memos = [];
8.830 - findMemoNodes(domNode, memos);
8.831 - for (var i = 0, j = memos.length; i < j; i++) {
8.832 - var node = memos[i].domNode;
8.833 - var combinedParams = [node];
8.834 - if (extraCallbackParamsArray)
8.835 - ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
8.836 - ko.memoization.unmemoize(memos[i].memoId, combinedParams);
8.837 - node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
8.838 - if (node.parentNode)
8.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)
8.840 - }
8.841 - },
8.842 -
8.843 - parseMemoText: function (memoText) {
8.844 - var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
8.845 - return match ? match[1] : null;
8.846 - }
8.847 - };
8.848 -})();
8.849 -
8.850 -ko.exportSymbol('memoization', ko.memoization);
8.851 -ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
8.852 -ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
8.853 -ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
8.854 -ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
8.855 -ko.extenders = {
8.856 - 'throttle': function(target, timeout) {
8.857 - // Throttling means two things:
8.858 -
8.859 - // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
8.860 - // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
8.861 - target['throttleEvaluation'] = timeout;
8.862 -
8.863 - // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
8.864 - // so the target cannot change value synchronously or faster than a certain rate
8.865 - var writeTimeoutInstance = null;
8.866 - return ko.dependentObservable({
8.867 - 'read': target,
8.868 - 'write': function(value) {
8.869 - clearTimeout(writeTimeoutInstance);
8.870 - writeTimeoutInstance = setTimeout(function() {
8.871 - target(value);
8.872 - }, timeout);
8.873 - }
8.874 - });
8.875 - },
8.876 -
8.877 - 'notify': function(target, notifyWhen) {
8.878 - target["equalityComparer"] = notifyWhen == "always"
8.879 - ? function() { return false } // Treat all values as not equal
8.880 - : ko.observable["fn"]["equalityComparer"];
8.881 - return target;
8.882 - }
8.883 -};
8.884 -
8.885 -function applyExtenders(requestedExtenders) {
8.886 - var target = this;
8.887 - if (requestedExtenders) {
8.888 - for (var key in requestedExtenders) {
8.889 - var extenderHandler = ko.extenders[key];
8.890 - if (typeof extenderHandler == 'function') {
8.891 - target = extenderHandler(target, requestedExtenders[key]);
8.892 - }
8.893 - }
8.894 - }
8.895 - return target;
8.896 -}
8.897 -
8.898 -ko.exportSymbol('extenders', ko.extenders);
8.899 -
8.900 -ko.subscription = function (target, callback, disposeCallback) {
8.901 - this.target = target;
8.902 - this.callback = callback;
8.903 - this.disposeCallback = disposeCallback;
8.904 - ko.exportProperty(this, 'dispose', this.dispose);
8.905 -};
8.906 -ko.subscription.prototype.dispose = function () {
8.907 - this.isDisposed = true;
8.908 - this.disposeCallback();
8.909 -};
8.910 -
8.911 -ko.subscribable = function () {
8.912 - this._subscriptions = {};
8.913 -
8.914 - ko.utils.extend(this, ko.subscribable['fn']);
8.915 - ko.exportProperty(this, 'subscribe', this.subscribe);
8.916 - ko.exportProperty(this, 'extend', this.extend);
8.917 - ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
8.918 -}
8.919 -
8.920 -var defaultEvent = "change";
8.921 -
8.922 -ko.subscribable['fn'] = {
8.923 - subscribe: function (callback, callbackTarget, event) {
8.924 - event = event || defaultEvent;
8.925 - var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
8.926 -
8.927 - var subscription = new ko.subscription(this, boundCallback, function () {
8.928 - ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
8.929 - }.bind(this));
8.930 -
8.931 - if (!this._subscriptions[event])
8.932 - this._subscriptions[event] = [];
8.933 - this._subscriptions[event].push(subscription);
8.934 - return subscription;
8.935 - },
8.936 -
8.937 - "notifySubscribers": function (valueToNotify, event) {
8.938 - event = event || defaultEvent;
8.939 - if (this._subscriptions[event]) {
8.940 - ko.dependencyDetection.ignore(function() {
8.941 - ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
8.942 - // In case a subscription was disposed during the arrayForEach cycle, check
8.943 - // for isDisposed on each subscription before invoking its callback
8.944 - if (subscription && (subscription.isDisposed !== true))
8.945 - subscription.callback(valueToNotify);
8.946 - });
8.947 - }, this);
8.948 - }
8.949 - },
8.950 -
8.951 - getSubscriptionsCount: function () {
8.952 - var total = 0;
8.953 - for (var eventName in this._subscriptions) {
8.954 - if (this._subscriptions.hasOwnProperty(eventName))
8.955 - total += this._subscriptions[eventName].length;
8.956 - }
8.957 - return total;
8.958 - },
8.959 -
8.960 - extend: applyExtenders
8.961 -};
8.962 -
8.963 -
8.964 -ko.isSubscribable = function (instance) {
8.965 - return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
8.966 -};
8.967 -
8.968 -ko.exportSymbol('subscribable', ko.subscribable);
8.969 -ko.exportSymbol('isSubscribable', ko.isSubscribable);
8.970 -
8.971 -ko.dependencyDetection = (function () {
8.972 - var _frames = [];
8.973 -
8.974 - return {
8.975 - begin: function (callback) {
8.976 - _frames.push({ callback: callback, distinctDependencies:[] });
8.977 - },
8.978 -
8.979 - end: function () {
8.980 - _frames.pop();
8.981 - },
8.982 -
8.983 - registerDependency: function (subscribable) {
8.984 - if (!ko.isSubscribable(subscribable))
8.985 - throw new Error("Only subscribable things can act as dependencies");
8.986 - if (_frames.length > 0) {
8.987 - var topFrame = _frames[_frames.length - 1];
8.988 - if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
8.989 - return;
8.990 - topFrame.distinctDependencies.push(subscribable);
8.991 - topFrame.callback(subscribable);
8.992 - }
8.993 - },
8.994 -
8.995 - ignore: function(callback, callbackTarget, callbackArgs) {
8.996 - try {
8.997 - _frames.push(null);
8.998 - return callback.apply(callbackTarget, callbackArgs || []);
8.999 - } finally {
8.1000 - _frames.pop();
8.1001 - }
8.1002 - }
8.1003 - };
8.1004 -})();
8.1005 -var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
8.1006 -
8.1007 -ko.observable = function (initialValue) {
8.1008 - var _latestValue = initialValue;
8.1009 -
8.1010 - function observable() {
8.1011 - if (arguments.length > 0) {
8.1012 - // Write
8.1013 -
8.1014 - // Ignore writes if the value hasn't changed
8.1015 - if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
8.1016 - observable.valueWillMutate();
8.1017 - _latestValue = arguments[0];
8.1018 - if (DEBUG) observable._latestValue = _latestValue;
8.1019 - observable.valueHasMutated();
8.1020 - }
8.1021 - return this; // Permits chained assignments
8.1022 - }
8.1023 - else {
8.1024 - // Read
8.1025 - ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
8.1026 - return _latestValue;
8.1027 - }
8.1028 - }
8.1029 - if (DEBUG) observable._latestValue = _latestValue;
8.1030 - ko.subscribable.call(observable);
8.1031 - observable.peek = function() { return _latestValue };
8.1032 - observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
8.1033 - observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
8.1034 - ko.utils.extend(observable, ko.observable['fn']);
8.1035 -
8.1036 - ko.exportProperty(observable, 'peek', observable.peek);
8.1037 - ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
8.1038 - ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
8.1039 -
8.1040 - return observable;
8.1041 -}
8.1042 -
8.1043 -ko.observable['fn'] = {
8.1044 - "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
8.1045 - var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
8.1046 - return oldValueIsPrimitive ? (a === b) : false;
8.1047 - }
8.1048 -};
8.1049 -
8.1050 -var protoProperty = ko.observable.protoProperty = "__ko_proto__";
8.1051 -ko.observable['fn'][protoProperty] = ko.observable;
8.1052 -
8.1053 -ko.hasPrototype = function(instance, prototype) {
8.1054 - if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
8.1055 - if (instance[protoProperty] === prototype) return true;
8.1056 - return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
8.1057 -};
8.1058 -
8.1059 -ko.isObservable = function (instance) {
8.1060 - return ko.hasPrototype(instance, ko.observable);
8.1061 -}
8.1062 -ko.isWriteableObservable = function (instance) {
8.1063 - // Observable
8.1064 - if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
8.1065 - return true;
8.1066 - // Writeable dependent observable
8.1067 - if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
8.1068 - return true;
8.1069 - // Anything else
8.1070 - return false;
8.1071 -}
8.1072 -
8.1073 -
8.1074 -ko.exportSymbol('observable', ko.observable);
8.1075 -ko.exportSymbol('isObservable', ko.isObservable);
8.1076 -ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
8.1077 -ko.observableArray = function (initialValues) {
8.1078 - if (arguments.length == 0) {
8.1079 - // Zero-parameter constructor initializes to empty array
8.1080 - initialValues = [];
8.1081 - }
8.1082 - if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
8.1083 - throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
8.1084 -
8.1085 - var result = ko.observable(initialValues);
8.1086 - ko.utils.extend(result, ko.observableArray['fn']);
8.1087 - return result;
8.1088 -}
8.1089 -
8.1090 -ko.observableArray['fn'] = {
8.1091 - 'remove': function (valueOrPredicate) {
8.1092 - var underlyingArray = this.peek();
8.1093 - var removedValues = [];
8.1094 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
8.1095 - for (var i = 0; i < underlyingArray.length; i++) {
8.1096 - var value = underlyingArray[i];
8.1097 - if (predicate(value)) {
8.1098 - if (removedValues.length === 0) {
8.1099 - this.valueWillMutate();
8.1100 - }
8.1101 - removedValues.push(value);
8.1102 - underlyingArray.splice(i, 1);
8.1103 - i--;
8.1104 - }
8.1105 - }
8.1106 - if (removedValues.length) {
8.1107 - this.valueHasMutated();
8.1108 - }
8.1109 - return removedValues;
8.1110 - },
8.1111 -
8.1112 - 'removeAll': function (arrayOfValues) {
8.1113 - // If you passed zero args, we remove everything
8.1114 - if (arrayOfValues === undefined) {
8.1115 - var underlyingArray = this.peek();
8.1116 - var allValues = underlyingArray.slice(0);
8.1117 - this.valueWillMutate();
8.1118 - underlyingArray.splice(0, underlyingArray.length);
8.1119 - this.valueHasMutated();
8.1120 - return allValues;
8.1121 - }
8.1122 - // If you passed an arg, we interpret it as an array of entries to remove
8.1123 - if (!arrayOfValues)
8.1124 - return [];
8.1125 - return this['remove'](function (value) {
8.1126 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
8.1127 - });
8.1128 - },
8.1129 -
8.1130 - 'destroy': function (valueOrPredicate) {
8.1131 - var underlyingArray = this.peek();
8.1132 - var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
8.1133 - this.valueWillMutate();
8.1134 - for (var i = underlyingArray.length - 1; i >= 0; i--) {
8.1135 - var value = underlyingArray[i];
8.1136 - if (predicate(value))
8.1137 - underlyingArray[i]["_destroy"] = true;
8.1138 - }
8.1139 - this.valueHasMutated();
8.1140 - },
8.1141 -
8.1142 - 'destroyAll': function (arrayOfValues) {
8.1143 - // If you passed zero args, we destroy everything
8.1144 - if (arrayOfValues === undefined)
8.1145 - return this['destroy'](function() { return true });
8.1146 -
8.1147 - // If you passed an arg, we interpret it as an array of entries to destroy
8.1148 - if (!arrayOfValues)
8.1149 - return [];
8.1150 - return this['destroy'](function (value) {
8.1151 - return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
8.1152 - });
8.1153 - },
8.1154 -
8.1155 - 'indexOf': function (item) {
8.1156 - var underlyingArray = this();
8.1157 - return ko.utils.arrayIndexOf(underlyingArray, item);
8.1158 - },
8.1159 -
8.1160 - 'replace': function(oldItem, newItem) {
8.1161 - var index = this['indexOf'](oldItem);
8.1162 - if (index >= 0) {
8.1163 - this.valueWillMutate();
8.1164 - this.peek()[index] = newItem;
8.1165 - this.valueHasMutated();
8.1166 - }
8.1167 - }
8.1168 -}
8.1169 -
8.1170 -// Populate ko.observableArray.fn with read/write functions from native arrays
8.1171 -// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
8.1172 -// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
8.1173 -ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
8.1174 - ko.observableArray['fn'][methodName] = function () {
8.1175 - // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
8.1176 - // (for consistency with mutating regular observables)
8.1177 - var underlyingArray = this.peek();
8.1178 - this.valueWillMutate();
8.1179 - var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
8.1180 - this.valueHasMutated();
8.1181 - return methodCallResult;
8.1182 - };
8.1183 -});
8.1184 -
8.1185 -// Populate ko.observableArray.fn with read-only functions from native arrays
8.1186 -ko.utils.arrayForEach(["slice"], function (methodName) {
8.1187 - ko.observableArray['fn'][methodName] = function () {
8.1188 - var underlyingArray = this();
8.1189 - return underlyingArray[methodName].apply(underlyingArray, arguments);
8.1190 - };
8.1191 -});
8.1192 -
8.1193 -ko.exportSymbol('observableArray', ko.observableArray);
8.1194 -ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
8.1195 - var _latestValue,
8.1196 - _hasBeenEvaluated = false,
8.1197 - _isBeingEvaluated = false,
8.1198 - readFunction = evaluatorFunctionOrOptions;
8.1199 -
8.1200 - if (readFunction && typeof readFunction == "object") {
8.1201 - // Single-parameter syntax - everything is on this "options" param
8.1202 - options = readFunction;
8.1203 - readFunction = options["read"];
8.1204 - } else {
8.1205 - // Multi-parameter syntax - construct the options according to the params passed
8.1206 - options = options || {};
8.1207 - if (!readFunction)
8.1208 - readFunction = options["read"];
8.1209 - }
8.1210 - if (typeof readFunction != "function")
8.1211 - throw new Error("Pass a function that returns the value of the ko.computed");
8.1212 -
8.1213 - function addSubscriptionToDependency(subscribable) {
8.1214 - _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
8.1215 - }
8.1216 -
8.1217 - function disposeAllSubscriptionsToDependencies() {
8.1218 - ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
8.1219 - subscription.dispose();
8.1220 - });
8.1221 - _subscriptionsToDependencies = [];
8.1222 - }
8.1223 -
8.1224 - function evaluatePossiblyAsync() {
8.1225 - var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
8.1226 - if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
8.1227 - clearTimeout(evaluationTimeoutInstance);
8.1228 - evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
8.1229 - } else
8.1230 - evaluateImmediate();
8.1231 - }
8.1232 -
8.1233 - function evaluateImmediate() {
8.1234 - if (_isBeingEvaluated) {
8.1235 - // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
8.1236 - // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
8.1237 - // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
8.1238 - // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
8.1239 - return;
8.1240 - }
8.1241 -
8.1242 - // Don't dispose on first evaluation, because the "disposeWhen" callback might
8.1243 - // e.g., dispose when the associated DOM element isn't in the doc, and it's not
8.1244 - // going to be in the doc until *after* the first evaluation
8.1245 - if (_hasBeenEvaluated && disposeWhen()) {
8.1246 - dispose();
8.1247 - return;
8.1248 - }
8.1249 -
8.1250 - _isBeingEvaluated = true;
8.1251 - try {
8.1252 - // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
8.1253 - // Then, during evaluation, we cross off any that are in fact still being used.
8.1254 - var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
8.1255 -
8.1256 - ko.dependencyDetection.begin(function(subscribable) {
8.1257 - var inOld;
8.1258 - if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
8.1259 - disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
8.1260 - else
8.1261 - addSubscriptionToDependency(subscribable); // Brand new subscription - add it
8.1262 - });
8.1263 -
8.1264 - var newValue = readFunction.call(evaluatorFunctionTarget);
8.1265 -
8.1266 - // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
8.1267 - for (var i = disposalCandidates.length - 1; i >= 0; i--) {
8.1268 - if (disposalCandidates[i])
8.1269 - _subscriptionsToDependencies.splice(i, 1)[0].dispose();
8.1270 - }
8.1271 - _hasBeenEvaluated = true;
8.1272 -
8.1273 - dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
8.1274 - _latestValue = newValue;
8.1275 - if (DEBUG) dependentObservable._latestValue = _latestValue;
8.1276 - } finally {
8.1277 - ko.dependencyDetection.end();
8.1278 - }
8.1279 -
8.1280 - dependentObservable["notifySubscribers"](_latestValue);
8.1281 - _isBeingEvaluated = false;
8.1282 - if (!_subscriptionsToDependencies.length)
8.1283 - dispose();
8.1284 - }
8.1285 -
8.1286 - function dependentObservable() {
8.1287 - if (arguments.length > 0) {
8.1288 - if (typeof writeFunction === "function") {
8.1289 - // Writing a value
8.1290 - writeFunction.apply(evaluatorFunctionTarget, arguments);
8.1291 - } else {
8.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.");
8.1293 - }
8.1294 - return this; // Permits chained assignments
8.1295 - } else {
8.1296 - // Reading the value
8.1297 - if (!_hasBeenEvaluated)
8.1298 - evaluateImmediate();
8.1299 - ko.dependencyDetection.registerDependency(dependentObservable);
8.1300 - return _latestValue;
8.1301 - }
8.1302 - }
8.1303 -
8.1304 - function peek() {
8.1305 - if (!_hasBeenEvaluated)
8.1306 - evaluateImmediate();
8.1307 - return _latestValue;
8.1308 - }
8.1309 -
8.1310 - function isActive() {
8.1311 - return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
8.1312 - }
8.1313 -
8.1314 - // By here, "options" is always non-null
8.1315 - var writeFunction = options["write"],
8.1316 - disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
8.1317 - disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
8.1318 - dispose = disposeAllSubscriptionsToDependencies,
8.1319 - _subscriptionsToDependencies = [],
8.1320 - evaluationTimeoutInstance = null;
8.1321 -
8.1322 - if (!evaluatorFunctionTarget)
8.1323 - evaluatorFunctionTarget = options["owner"];
8.1324 -
8.1325 - dependentObservable.peek = peek;
8.1326 - dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
8.1327 - dependentObservable.hasWriteFunction = typeof options["write"] === "function";
8.1328 - dependentObservable.dispose = function () { dispose(); };
8.1329 - dependentObservable.isActive = isActive;
8.1330 - dependentObservable.valueHasMutated = function() {
8.1331 - _hasBeenEvaluated = false;
8.1332 - evaluateImmediate();
8.1333 - };
8.1334 -
8.1335 - ko.subscribable.call(dependentObservable);
8.1336 - ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
8.1337 -
8.1338 - ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
8.1339 - ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
8.1340 - ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
8.1341 - ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
8.1342 -
8.1343 - // Evaluate, unless deferEvaluation is true
8.1344 - if (options['deferEvaluation'] !== true)
8.1345 - evaluateImmediate();
8.1346 -
8.1347 - // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
8.1348 - // But skip if isActive is false (there will never be any dependencies to dispose).
8.1349 - // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
8.1350 - // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
8.1351 - if (disposeWhenNodeIsRemoved && isActive()) {
8.1352 - dispose = function() {
8.1353 - ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
8.1354 - disposeAllSubscriptionsToDependencies();
8.1355 - };
8.1356 - ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
8.1357 - var existingDisposeWhenFunction = disposeWhen;
8.1358 - disposeWhen = function () {
8.1359 - return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
8.1360 - }
8.1361 - }
8.1362 -
8.1363 - return dependentObservable;
8.1364 -};
8.1365 -
8.1366 -ko.isComputed = function(instance) {
8.1367 - return ko.hasPrototype(instance, ko.dependentObservable);
8.1368 -};
8.1369 -
8.1370 -var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
8.1371 -ko.dependentObservable[protoProp] = ko.observable;
8.1372 -
8.1373 -ko.dependentObservable['fn'] = {};
8.1374 -ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
8.1375 -
8.1376 -ko.exportSymbol('dependentObservable', ko.dependentObservable);
8.1377 -ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
8.1378 -ko.exportSymbol('isComputed', ko.isComputed);
8.1379 -
8.1380 -(function() {
8.1381 - var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
8.1382 -
8.1383 - ko.toJS = function(rootObject) {
8.1384 - if (arguments.length == 0)
8.1385 - throw new Error("When calling ko.toJS, pass the object you want to convert.");
8.1386 -
8.1387 - // We just unwrap everything at every level in the object graph
8.1388 - return mapJsObjectGraph(rootObject, function(valueToMap) {
8.1389 - // Loop because an observable's value might in turn be another observable wrapper
8.1390 - for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
8.1391 - valueToMap = valueToMap();
8.1392 - return valueToMap;
8.1393 - });
8.1394 - };
8.1395 -
8.1396 - ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
8.1397 - var plainJavaScriptObject = ko.toJS(rootObject);
8.1398 - return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
8.1399 - };
8.1400 -
8.1401 - function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
8.1402 - visitedObjects = visitedObjects || new objectLookup();
8.1403 -
8.1404 - rootObject = mapInputCallback(rootObject);
8.1405 - var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
8.1406 - if (!canHaveProperties)
8.1407 - return rootObject;
8.1408 -
8.1409 - var outputProperties = rootObject instanceof Array ? [] : {};
8.1410 - visitedObjects.save(rootObject, outputProperties);
8.1411 -
8.1412 - visitPropertiesOrArrayEntries(rootObject, function(indexer) {
8.1413 - var propertyValue = mapInputCallback(rootObject[indexer]);
8.1414 -
8.1415 - switch (typeof propertyValue) {
8.1416 - case "boolean":
8.1417 - case "number":
8.1418 - case "string":
8.1419 - case "function":
8.1420 - outputProperties[indexer] = propertyValue;
8.1421 - break;
8.1422 - case "object":
8.1423 - case "undefined":
8.1424 - var previouslyMappedValue = visitedObjects.get(propertyValue);
8.1425 - outputProperties[indexer] = (previouslyMappedValue !== undefined)
8.1426 - ? previouslyMappedValue
8.1427 - : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
8.1428 - break;
8.1429 - }
8.1430 - });
8.1431 -
8.1432 - return outputProperties;
8.1433 - }
8.1434 -
8.1435 - function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
8.1436 - if (rootObject instanceof Array) {
8.1437 - for (var i = 0; i < rootObject.length; i++)
8.1438 - visitorCallback(i);
8.1439 -
8.1440 - // For arrays, also respect toJSON property for custom mappings (fixes #278)
8.1441 - if (typeof rootObject['toJSON'] == 'function')
8.1442 - visitorCallback('toJSON');
8.1443 - } else {
8.1444 - for (var propertyName in rootObject)
8.1445 - visitorCallback(propertyName);
8.1446 - }
8.1447 - };
8.1448 -
8.1449 - function objectLookup() {
8.1450 - var keys = [];
8.1451 - var values = [];
8.1452 - this.save = function(key, value) {
8.1453 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
8.1454 - if (existingIndex >= 0)
8.1455 - values[existingIndex] = value;
8.1456 - else {
8.1457 - keys.push(key);
8.1458 - values.push(value);
8.1459 - }
8.1460 - };
8.1461 - this.get = function(key) {
8.1462 - var existingIndex = ko.utils.arrayIndexOf(keys, key);
8.1463 - return (existingIndex >= 0) ? values[existingIndex] : undefined;
8.1464 - };
8.1465 - };
8.1466 -})();
8.1467 -
8.1468 -ko.exportSymbol('toJS', ko.toJS);
8.1469 -ko.exportSymbol('toJSON', ko.toJSON);
8.1470 -(function () {
8.1471 - var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
8.1472 -
8.1473 - // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
8.1474 - // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
8.1475 - // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
8.1476 - ko.selectExtensions = {
8.1477 - readValue : function(element) {
8.1478 - switch (ko.utils.tagNameLower(element)) {
8.1479 - case 'option':
8.1480 - if (element[hasDomDataExpandoProperty] === true)
8.1481 - return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
8.1482 - return ko.utils.ieVersion <= 7
8.1483 - ? (element.getAttributeNode('value').specified ? element.value : element.text)
8.1484 - : element.value;
8.1485 - case 'select':
8.1486 - return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
8.1487 - default:
8.1488 - return element.value;
8.1489 - }
8.1490 - },
8.1491 -
8.1492 - writeValue: function(element, value) {
8.1493 - switch (ko.utils.tagNameLower(element)) {
8.1494 - case 'option':
8.1495 - switch(typeof value) {
8.1496 - case "string":
8.1497 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
8.1498 - if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
8.1499 - delete element[hasDomDataExpandoProperty];
8.1500 - }
8.1501 - element.value = value;
8.1502 - break;
8.1503 - default:
8.1504 - // Store arbitrary object using DomData
8.1505 - ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
8.1506 - element[hasDomDataExpandoProperty] = true;
8.1507 -
8.1508 - // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
8.1509 - element.value = typeof value === "number" ? value : "";
8.1510 - break;
8.1511 - }
8.1512 - break;
8.1513 - case 'select':
8.1514 - for (var i = element.options.length - 1; i >= 0; i--) {
8.1515 - if (ko.selectExtensions.readValue(element.options[i]) == value) {
8.1516 - element.selectedIndex = i;
8.1517 - break;
8.1518 - }
8.1519 - }
8.1520 - break;
8.1521 - default:
8.1522 - if ((value === null) || (value === undefined))
8.1523 - value = "";
8.1524 - element.value = value;
8.1525 - break;
8.1526 - }
8.1527 - }
8.1528 - };
8.1529 -})();
8.1530 -
8.1531 -ko.exportSymbol('selectExtensions', ko.selectExtensions);
8.1532 -ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
8.1533 -ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
8.1534 -ko.expressionRewriting = (function () {
8.1535 - var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
8.1536 - var javaScriptReservedWords = ["true", "false"];
8.1537 -
8.1538 - // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
8.1539 - // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
8.1540 - var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
8.1541 -
8.1542 - function restoreTokens(string, tokens) {
8.1543 - var prevValue = null;
8.1544 - while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
8.1545 - prevValue = string;
8.1546 - string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
8.1547 - return tokens[tokenIndex];
8.1548 - });
8.1549 - }
8.1550 - return string;
8.1551 - }
8.1552 -
8.1553 - function getWriteableValue(expression) {
8.1554 - if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
8.1555 - return false;
8.1556 - var match = expression.match(javaScriptAssignmentTarget);
8.1557 - return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
8.1558 - }
8.1559 -
8.1560 - function ensureQuoted(key) {
8.1561 - var trimmedKey = ko.utils.stringTrim(key);
8.1562 - switch (trimmedKey.length && trimmedKey.charAt(0)) {
8.1563 - case "'":
8.1564 - case '"':
8.1565 - return key;
8.1566 - default:
8.1567 - return "'" + trimmedKey + "'";
8.1568 - }
8.1569 - }
8.1570 -
8.1571 - return {
8.1572 - bindingRewriteValidators: [],
8.1573 -
8.1574 - parseObjectLiteral: function(objectLiteralString) {
8.1575 - // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
8.1576 - // that is sufficient just to split an object literal string into a set of top-level key-value pairs
8.1577 -
8.1578 - var str = ko.utils.stringTrim(objectLiteralString);
8.1579 - if (str.length < 3)
8.1580 - return [];
8.1581 - if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
8.1582 - str = str.substring(1, str.length - 1);
8.1583 -
8.1584 - // Pull out any string literals and regex literals
8.1585 - var tokens = [];
8.1586 - var tokenStart = null, tokenEndChar;
8.1587 - for (var position = 0; position < str.length; position++) {
8.1588 - var c = str.charAt(position);
8.1589 - if (tokenStart === null) {
8.1590 - switch (c) {
8.1591 - case '"':
8.1592 - case "'":
8.1593 - case "/":
8.1594 - tokenStart = position;
8.1595 - tokenEndChar = c;
8.1596 - break;
8.1597 - }
8.1598 - } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
8.1599 - var token = str.substring(tokenStart, position + 1);
8.1600 - tokens.push(token);
8.1601 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
8.1602 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
8.1603 - position -= (token.length - replacement.length);
8.1604 - tokenStart = null;
8.1605 - }
8.1606 - }
8.1607 -
8.1608 - // Next pull out balanced paren, brace, and bracket blocks
8.1609 - tokenStart = null;
8.1610 - tokenEndChar = null;
8.1611 - var tokenDepth = 0, tokenStartChar = null;
8.1612 - for (var position = 0; position < str.length; position++) {
8.1613 - var c = str.charAt(position);
8.1614 - if (tokenStart === null) {
8.1615 - switch (c) {
8.1616 - case "{": tokenStart = position; tokenStartChar = c;
8.1617 - tokenEndChar = "}";
8.1618 - break;
8.1619 - case "(": tokenStart = position; tokenStartChar = c;
8.1620 - tokenEndChar = ")";
8.1621 - break;
8.1622 - case "[": tokenStart = position; tokenStartChar = c;
8.1623 - tokenEndChar = "]";
8.1624 - break;
8.1625 - }
8.1626 - }
8.1627 -
8.1628 - if (c === tokenStartChar)
8.1629 - tokenDepth++;
8.1630 - else if (c === tokenEndChar) {
8.1631 - tokenDepth--;
8.1632 - if (tokenDepth === 0) {
8.1633 - var token = str.substring(tokenStart, position + 1);
8.1634 - tokens.push(token);
8.1635 - var replacement = "@ko_token_" + (tokens.length - 1) + "@";
8.1636 - str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
8.1637 - position -= (token.length - replacement.length);
8.1638 - tokenStart = null;
8.1639 - }
8.1640 - }
8.1641 - }
8.1642 -
8.1643 - // Now we can safely split on commas to get the key/value pairs
8.1644 - var result = [];
8.1645 - var keyValuePairs = str.split(",");
8.1646 - for (var i = 0, j = keyValuePairs.length; i < j; i++) {
8.1647 - var pair = keyValuePairs[i];
8.1648 - var colonPos = pair.indexOf(":");
8.1649 - if ((colonPos > 0) && (colonPos < pair.length - 1)) {
8.1650 - var key = pair.substring(0, colonPos);
8.1651 - var value = pair.substring(colonPos + 1);
8.1652 - result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
8.1653 - } else {
8.1654 - result.push({ 'unknown': restoreTokens(pair, tokens) });
8.1655 - }
8.1656 - }
8.1657 - return result;
8.1658 - },
8.1659 -
8.1660 - preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
8.1661 - var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
8.1662 - ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
8.1663 - : objectLiteralStringOrKeyValueArray;
8.1664 - var resultStrings = [], propertyAccessorResultStrings = [];
8.1665 -
8.1666 - var keyValueEntry;
8.1667 - for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
8.1668 - if (resultStrings.length > 0)
8.1669 - resultStrings.push(",");
8.1670 -
8.1671 - if (keyValueEntry['key']) {
8.1672 - var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
8.1673 - resultStrings.push(quotedKey);
8.1674 - resultStrings.push(":");
8.1675 - resultStrings.push(val);
8.1676 -
8.1677 - if (val = getWriteableValue(ko.utils.stringTrim(val))) {
8.1678 - if (propertyAccessorResultStrings.length > 0)
8.1679 - propertyAccessorResultStrings.push(", ");
8.1680 - propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
8.1681 - }
8.1682 - } else if (keyValueEntry['unknown']) {
8.1683 - resultStrings.push(keyValueEntry['unknown']);
8.1684 - }
8.1685 - }
8.1686 -
8.1687 - var combinedResult = resultStrings.join("");
8.1688 - if (propertyAccessorResultStrings.length > 0) {
8.1689 - var allPropertyAccessors = propertyAccessorResultStrings.join("");
8.1690 - combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
8.1691 - }
8.1692 -
8.1693 - return combinedResult;
8.1694 - },
8.1695 -
8.1696 - keyValueArrayContainsKey: function(keyValueArray, key) {
8.1697 - for (var i = 0; i < keyValueArray.length; i++)
8.1698 - if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
8.1699 - return true;
8.1700 - return false;
8.1701 - },
8.1702 -
8.1703 - // Internal, private KO utility for updating model properties from within bindings
8.1704 - // property: If the property being updated is (or might be) an observable, pass it here
8.1705 - // If it turns out to be a writable observable, it will be written to directly
8.1706 - // allBindingsAccessor: All bindings in the current execution context.
8.1707 - // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
8.1708 - // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
8.1709 - // value: The value to be written
8.1710 - // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
8.1711 - // it is !== existing value on that writable observable
8.1712 - writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
8.1713 - if (!property || !ko.isWriteableObservable(property)) {
8.1714 - var propWriters = allBindingsAccessor()['_ko_property_writers'];
8.1715 - if (propWriters && propWriters[key])
8.1716 - propWriters[key](value);
8.1717 - } else if (!checkIfDifferent || property.peek() !== value) {
8.1718 - property(value);
8.1719 - }
8.1720 - }
8.1721 - };
8.1722 -})();
8.1723 -
8.1724 -ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
8.1725 -ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
8.1726 -ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
8.1727 -ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
8.1728 -
8.1729 -// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
8.1730 -// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
8.1731 -ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
8.1732 -ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
8.1733 - // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
8.1734 - // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
8.1735 - // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
8.1736 - // of that virtual hierarchy
8.1737 - //
8.1738 - // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
8.1739 - // without having to scatter special cases all over the binding and templating code.
8.1740 -
8.1741 - // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
8.1742 - // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
8.1743 - // So, use node.text where available, and node.nodeValue elsewhere
8.1744 - var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
8.1745 -
8.1746 - var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
8.1747 - var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
8.1748 - var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
8.1749 -
8.1750 - function isStartComment(node) {
8.1751 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
8.1752 - }
8.1753 -
8.1754 - function isEndComment(node) {
8.1755 - return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
8.1756 - }
8.1757 -
8.1758 - function getVirtualChildren(startComment, allowUnbalanced) {
8.1759 - var currentNode = startComment;
8.1760 - var depth = 1;
8.1761 - var children = [];
8.1762 - while (currentNode = currentNode.nextSibling) {
8.1763 - if (isEndComment(currentNode)) {
8.1764 - depth--;
8.1765 - if (depth === 0)
8.1766 - return children;
8.1767 - }
8.1768 -
8.1769 - children.push(currentNode);
8.1770 -
8.1771 - if (isStartComment(currentNode))
8.1772 - depth++;
8.1773 - }
8.1774 - if (!allowUnbalanced)
8.1775 - throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
8.1776 - return null;
8.1777 - }
8.1778 -
8.1779 - function getMatchingEndComment(startComment, allowUnbalanced) {
8.1780 - var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
8.1781 - if (allVirtualChildren) {
8.1782 - if (allVirtualChildren.length > 0)
8.1783 - return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
8.1784 - return startComment.nextSibling;
8.1785 - } else
8.1786 - return null; // Must have no matching end comment, and allowUnbalanced is true
8.1787 - }
8.1788 -
8.1789 - function getUnbalancedChildTags(node) {
8.1790 - // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
8.1791 - // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
8.1792 - var childNode = node.firstChild, captureRemaining = null;
8.1793 - if (childNode) {
8.1794 - do {
8.1795 - if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
8.1796 - captureRemaining.push(childNode);
8.1797 - else if (isStartComment(childNode)) {
8.1798 - var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
8.1799 - if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
8.1800 - childNode = matchingEndComment;
8.1801 - else
8.1802 - captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
8.1803 - } else if (isEndComment(childNode)) {
8.1804 - captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
8.1805 - }
8.1806 - } while (childNode = childNode.nextSibling);
8.1807 - }
8.1808 - return captureRemaining;
8.1809 - }
8.1810 -
8.1811 - ko.virtualElements = {
8.1812 - allowedBindings: {},
8.1813 -
8.1814 - childNodes: function(node) {
8.1815 - return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
8.1816 - },
8.1817 -
8.1818 - emptyNode: function(node) {
8.1819 - if (!isStartComment(node))
8.1820 - ko.utils.emptyDomNode(node);
8.1821 - else {
8.1822 - var virtualChildren = ko.virtualElements.childNodes(node);
8.1823 - for (var i = 0, j = virtualChildren.length; i < j; i++)
8.1824 - ko.removeNode(virtualChildren[i]);
8.1825 - }
8.1826 - },
8.1827 -
8.1828 - setDomNodeChildren: function(node, childNodes) {
8.1829 - if (!isStartComment(node))
8.1830 - ko.utils.setDomNodeChildren(node, childNodes);
8.1831 - else {
8.1832 - ko.virtualElements.emptyNode(node);
8.1833 - var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
8.1834 - for (var i = 0, j = childNodes.length; i < j; i++)
8.1835 - endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
8.1836 - }
8.1837 - },
8.1838 -
8.1839 - prepend: function(containerNode, nodeToPrepend) {
8.1840 - if (!isStartComment(containerNode)) {
8.1841 - if (containerNode.firstChild)
8.1842 - containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
8.1843 - else
8.1844 - containerNode.appendChild(nodeToPrepend);
8.1845 - } else {
8.1846 - // Start comments must always have a parent and at least one following sibling (the end comment)
8.1847 - containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
8.1848 - }
8.1849 - },
8.1850 -
8.1851 - insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
8.1852 - if (!insertAfterNode) {
8.1853 - ko.virtualElements.prepend(containerNode, nodeToInsert);
8.1854 - } else if (!isStartComment(containerNode)) {
8.1855 - // Insert after insertion point
8.1856 - if (insertAfterNode.nextSibling)
8.1857 - containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
8.1858 - else
8.1859 - containerNode.appendChild(nodeToInsert);
8.1860 - } else {
8.1861 - // Children of start comments must always have a parent and at least one following sibling (the end comment)
8.1862 - containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
8.1863 - }
8.1864 - },
8.1865 -
8.1866 - firstChild: function(node) {
8.1867 - if (!isStartComment(node))
8.1868 - return node.firstChild;
8.1869 - if (!node.nextSibling || isEndComment(node.nextSibling))
8.1870 - return null;
8.1871 - return node.nextSibling;
8.1872 - },
8.1873 -
8.1874 - nextSibling: function(node) {
8.1875 - if (isStartComment(node))
8.1876 - node = getMatchingEndComment(node);
8.1877 - if (node.nextSibling && isEndComment(node.nextSibling))
8.1878 - return null;
8.1879 - return node.nextSibling;
8.1880 - },
8.1881 -
8.1882 - virtualNodeBindingValue: function(node) {
8.1883 - var regexMatch = isStartComment(node);
8.1884 - return regexMatch ? regexMatch[1] : null;
8.1885 - },
8.1886 -
8.1887 - normaliseVirtualElementDomStructure: function(elementVerified) {
8.1888 - // Workaround for https://github.com/SteveSanderson/knockout/issues/155
8.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
8.1890 - // that are direct descendants of <ul> into the preceding <li>)
8.1891 - if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
8.1892 - return;
8.1893 -
8.1894 - // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
8.1895 - // must be intended to appear *after* that child, so move them there.
8.1896 - var childNode = elementVerified.firstChild;
8.1897 - if (childNode) {
8.1898 - do {
8.1899 - if (childNode.nodeType === 1) {
8.1900 - var unbalancedTags = getUnbalancedChildTags(childNode);
8.1901 - if (unbalancedTags) {
8.1902 - // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
8.1903 - var nodeToInsertBefore = childNode.nextSibling;
8.1904 - for (var i = 0; i < unbalancedTags.length; i++) {
8.1905 - if (nodeToInsertBefore)
8.1906 - elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
8.1907 - else
8.1908 - elementVerified.appendChild(unbalancedTags[i]);
8.1909 - }
8.1910 - }
8.1911 - }
8.1912 - } while (childNode = childNode.nextSibling);
8.1913 - }
8.1914 - }
8.1915 - };
8.1916 -})();
8.1917 -ko.exportSymbol('virtualElements', ko.virtualElements);
8.1918 -ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
8.1919 -ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
8.1920 -//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
8.1921 -ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
8.1922 -//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
8.1923 -ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
8.1924 -ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
8.1925 -(function() {
8.1926 - var defaultBindingAttributeName = "data-bind";
8.1927 -
8.1928 - ko.bindingProvider = function() {
8.1929 - this.bindingCache = {};
8.1930 - };
8.1931 -
8.1932 - ko.utils.extend(ko.bindingProvider.prototype, {
8.1933 - 'nodeHasBindings': function(node) {
8.1934 - switch (node.nodeType) {
8.1935 - case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
8.1936 - case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
8.1937 - default: return false;
8.1938 - }
8.1939 - },
8.1940 -
8.1941 - 'getBindings': function(node, bindingContext) {
8.1942 - var bindingsString = this['getBindingsString'](node, bindingContext);
8.1943 - return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
8.1944 - },
8.1945 -
8.1946 - // The following function is only used internally by this default provider.
8.1947 - // It's not part of the interface definition for a general binding provider.
8.1948 - 'getBindingsString': function(node, bindingContext) {
8.1949 - switch (node.nodeType) {
8.1950 - case 1: return node.getAttribute(defaultBindingAttributeName); // Element
8.1951 - case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
8.1952 - default: return null;
8.1953 - }
8.1954 - },
8.1955 -
8.1956 - // The following function is only used internally by this default provider.
8.1957 - // It's not part of the interface definition for a general binding provider.
8.1958 - 'parseBindingsString': function(bindingsString, bindingContext, node) {
8.1959 - try {
8.1960 - var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
8.1961 - return bindingFunction(bindingContext, node);
8.1962 - } catch (ex) {
8.1963 - throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
8.1964 - }
8.1965 - }
8.1966 - });
8.1967 -
8.1968 - ko.bindingProvider['instance'] = new ko.bindingProvider();
8.1969 -
8.1970 - function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
8.1971 - var cacheKey = bindingsString;
8.1972 - return cache[cacheKey]
8.1973 - || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
8.1974 - }
8.1975 -
8.1976 - function createBindingsStringEvaluator(bindingsString) {
8.1977 - // Build the source for a function that evaluates "expression"
8.1978 - // For each scope variable, add an extra level of "with" nesting
8.1979 - // Example result: with(sc1) { with(sc0) { return (expression) } }
8.1980 - var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
8.1981 - functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
8.1982 - return new Function("$context", "$element", functionBody);
8.1983 - }
8.1984 -})();
8.1985 -
8.1986 -ko.exportSymbol('bindingProvider', ko.bindingProvider);
8.1987 -(function () {
8.1988 - ko.bindingHandlers = {};
8.1989 -
8.1990 - ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
8.1991 - if (parentBindingContext) {
8.1992 - ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
8.1993 - this['$parentContext'] = parentBindingContext;
8.1994 - this['$parent'] = parentBindingContext['$data'];
8.1995 - this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
8.1996 - this['$parents'].unshift(this['$parent']);
8.1997 - } else {
8.1998 - this['$parents'] = [];
8.1999 - this['$root'] = dataItem;
8.2000 - // Export 'ko' in the binding context so it will be available in bindings and templates
8.2001 - // even if 'ko' isn't exported as a global, such as when using an AMD loader.
8.2002 - // See https://github.com/SteveSanderson/knockout/issues/490
8.2003 - this['ko'] = ko;
8.2004 - }
8.2005 - this['$data'] = dataItem;
8.2006 - if (dataItemAlias)
8.2007 - this[dataItemAlias] = dataItem;
8.2008 - }
8.2009 - ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
8.2010 - return new ko.bindingContext(dataItem, this, dataItemAlias);
8.2011 - };
8.2012 - ko.bindingContext.prototype['extend'] = function(properties) {
8.2013 - var clone = ko.utils.extend(new ko.bindingContext(), this);
8.2014 - return ko.utils.extend(clone, properties);
8.2015 - };
8.2016 -
8.2017 - function validateThatBindingIsAllowedForVirtualElements(bindingName) {
8.2018 - var validator = ko.virtualElements.allowedBindings[bindingName];
8.2019 - if (!validator)
8.2020 - throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
8.2021 - }
8.2022 -
8.2023 - function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
8.2024 - var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
8.2025 - while (currentChild = nextInQueue) {
8.2026 - // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
8.2027 - nextInQueue = ko.virtualElements.nextSibling(currentChild);
8.2028 - applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
8.2029 - }
8.2030 - }
8.2031 -
8.2032 - function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
8.2033 - var shouldBindDescendants = true;
8.2034 -
8.2035 - // Perf optimisation: Apply bindings only if...
8.2036 - // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
8.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
8.2038 - // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
8.2039 - var isElement = (nodeVerified.nodeType === 1);
8.2040 - if (isElement) // Workaround IE <= 8 HTML parsing weirdness
8.2041 - ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
8.2042 -
8.2043 - var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
8.2044 - || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
8.2045 - if (shouldApplyBindings)
8.2046 - shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
8.2047 -
8.2048 - if (shouldBindDescendants) {
8.2049 - // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
8.2050 - // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
8.2051 - // hence bindingContextsMayDifferFromDomParentElement is false
8.2052 - // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
8.2053 - // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
8.2054 - // hence bindingContextsMayDifferFromDomParentElement is true
8.2055 - applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
8.2056 - }
8.2057 - }
8.2058 -
8.2059 - function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
8.2060 - // Need to be sure that inits are only run once, and updates never run until all the inits have been run
8.2061 - var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
8.2062 -
8.2063 - // Each time the dependentObservable is evaluated (after data changes),
8.2064 - // the binding attribute is reparsed so that it can pick out the correct
8.2065 - // model properties in the context of the changed data.
8.2066 - // DOM event callbacks need to be able to access this changed data,
8.2067 - // so we need a single parsedBindings variable (shared by all callbacks
8.2068 - // associated with this node's bindings) that all the closures can access.
8.2069 - var parsedBindings;
8.2070 - function makeValueAccessor(bindingKey) {
8.2071 - return function () { return parsedBindings[bindingKey] }
8.2072 - }
8.2073 - function parsedBindingsAccessor() {
8.2074 - return parsedBindings;
8.2075 - }
8.2076 -
8.2077 - var bindingHandlerThatControlsDescendantBindings;
8.2078 - ko.dependentObservable(
8.2079 - function () {
8.2080 - // Ensure we have a nonnull binding context to work with
8.2081 - var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
8.2082 - ? viewModelOrBindingContext
8.2083 - : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
8.2084 - var viewModel = bindingContextInstance['$data'];
8.2085 -
8.2086 - // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
8.2087 - // we can easily recover it just by scanning up the node's ancestors in the DOM
8.2088 - // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
8.2089 - if (bindingContextMayDifferFromDomParentElement)
8.2090 - ko.storedBindingContextForNode(node, bindingContextInstance);
8.2091 -
8.2092 - // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
8.2093 - var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
8.2094 - parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
8.2095 -
8.2096 - if (parsedBindings) {
8.2097 - // First run all the inits, so bindings can register for notification on changes
8.2098 - if (initPhase === 0) {
8.2099 - initPhase = 1;
8.2100 - for (var bindingKey in parsedBindings) {
8.2101 - var binding = ko.bindingHandlers[bindingKey];
8.2102 - if (binding && node.nodeType === 8)
8.2103 - validateThatBindingIsAllowedForVirtualElements(bindingKey);
8.2104 -
8.2105 - if (binding && typeof binding["init"] == "function") {
8.2106 - var handlerInitFn = binding["init"];
8.2107 - var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
8.2108 -
8.2109 - // If this binding handler claims to control descendant bindings, make a note of this
8.2110 - if (initResult && initResult['controlsDescendantBindings']) {
8.2111 - if (bindingHandlerThatControlsDescendantBindings !== undefined)
8.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.");
8.2113 - bindingHandlerThatControlsDescendantBindings = bindingKey;
8.2114 - }
8.2115 - }
8.2116 - }
8.2117 - initPhase = 2;
8.2118 - }
8.2119 -
8.2120 - // ... then run all the updates, which might trigger changes even on the first evaluation
8.2121 - if (initPhase === 2) {
8.2122 - for (var bindingKey in parsedBindings) {
8.2123 - var binding = ko.bindingHandlers[bindingKey];
8.2124 - if (binding && typeof binding["update"] == "function") {
8.2125 - var handlerUpdateFn = binding["update"];
8.2126 - handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
8.2127 - }
8.2128 - }
8.2129 - }
8.2130 - }
8.2131 - },
8.2132 - null,
8.2133 - { disposeWhenNodeIsRemoved : node }
8.2134 - );
8.2135 -
8.2136 - return {
8.2137 - shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
8.2138 - };
8.2139 - };
8.2140 -
8.2141 - var storedBindingContextDomDataKey = "__ko_bindingContext__";
8.2142 - ko.storedBindingContextForNode = function (node, bindingContext) {
8.2143 - if (arguments.length == 2)
8.2144 - ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
8.2145 - else
8.2146 - return ko.utils.domData.get(node, storedBindingContextDomDataKey);
8.2147 - }
8.2148 -
8.2149 - ko.applyBindingsToNode = function (node, bindings, viewModel) {
8.2150 - if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
8.2151 - ko.virtualElements.normaliseVirtualElementDomStructure(node);
8.2152 - return applyBindingsToNodeInternal(node, bindings, viewModel, true);
8.2153 - };
8.2154 -
8.2155 - ko.applyBindingsToDescendants = function(viewModel, rootNode) {
8.2156 - if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
8.2157 - applyBindingsToDescendantsInternal(viewModel, rootNode, true);
8.2158 - };
8.2159 -
8.2160 - ko.applyBindings = function (viewModel, rootNode) {
8.2161 - if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
8.2162 - throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
8.2163 - rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
8.2164 -
8.2165 - applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
8.2166 - };
8.2167 -
8.2168 - // Retrieving binding context from arbitrary nodes
8.2169 - ko.contextFor = function(node) {
8.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)
8.2171 - switch (node.nodeType) {
8.2172 - case 1:
8.2173 - case 8:
8.2174 - var context = ko.storedBindingContextForNode(node);
8.2175 - if (context) return context;
8.2176 - if (node.parentNode) return ko.contextFor(node.parentNode);
8.2177 - break;
8.2178 - }
8.2179 - return undefined;
8.2180 - };
8.2181 - ko.dataFor = function(node) {
8.2182 - var context = ko.contextFor(node);
8.2183 - return context ? context['$data'] : undefined;
8.2184 - };
8.2185 -
8.2186 - ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
8.2187 - ko.exportSymbol('applyBindings', ko.applyBindings);
8.2188 - ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
8.2189 - ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
8.2190 - ko.exportSymbol('contextFor', ko.contextFor);
8.2191 - ko.exportSymbol('dataFor', ko.dataFor);
8.2192 -})();
8.2193 -var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
8.2194 -ko.bindingHandlers['attr'] = {
8.2195 - 'update': function(element, valueAccessor, allBindingsAccessor) {
8.2196 - var value = ko.utils.unwrapObservable(valueAccessor()) || {};
8.2197 - for (var attrName in value) {
8.2198 - if (typeof attrName == "string") {
8.2199 - var attrValue = ko.utils.unwrapObservable(value[attrName]);
8.2200 -
8.2201 - // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
8.2202 - // when someProp is a "no value"-like value (strictly null, false, or undefined)
8.2203 - // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
8.2204 - var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
8.2205 - if (toRemove)
8.2206 - element.removeAttribute(attrName);
8.2207 -
8.2208 - // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
8.2209 - // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
8.2210 - // but instead of figuring out the mode, we'll just set the attribute through the Javascript
8.2211 - // property for IE <= 8.
8.2212 - if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
8.2213 - attrName = attrHtmlToJavascriptMap[attrName];
8.2214 - if (toRemove)
8.2215 - element.removeAttribute(attrName);
8.2216 - else
8.2217 - element[attrName] = attrValue;
8.2218 - } else if (!toRemove) {
8.2219 - try {
8.2220 - element.setAttribute(attrName, attrValue.toString());
8.2221 - } catch (err) {
8.2222 - // ignore for now
8.2223 - if (console) {
8.2224 - console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
8.2225 - }
8.2226 - }
8.2227 - }
8.2228 -
8.2229 - // Treat "name" specially - although you can think of it as an attribute, it also needs
8.2230 - // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
8.2231 - // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
8.2232 - // entirely, and there's no strong reason to allow for such casing in HTML.
8.2233 - if (attrName === "name") {
8.2234 - ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
8.2235 - }
8.2236 - }
8.2237 - }
8.2238 - }
8.2239 -};
8.2240 -ko.bindingHandlers['checked'] = {
8.2241 - 'init': function (element, valueAccessor, allBindingsAccessor) {
8.2242 - var updateHandler = function() {
8.2243 - var valueToWrite;
8.2244 - if (element.type == "checkbox") {
8.2245 - valueToWrite = element.checked;
8.2246 - } else if ((element.type == "radio") && (element.checked)) {
8.2247 - valueToWrite = element.value;
8.2248 - } else {
8.2249 - return; // "checked" binding only responds to checkboxes and selected radio buttons
8.2250 - }
8.2251 -
8.2252 - var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
8.2253 - if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
8.2254 - // For checkboxes bound to an array, we add/remove the checkbox value to that array
8.2255 - // This works for both observable and non-observable arrays
8.2256 - var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
8.2257 - if (element.checked && (existingEntryIndex < 0))
8.2258 - modelValue.push(element.value);
8.2259 - else if ((!element.checked) && (existingEntryIndex >= 0))
8.2260 - modelValue.splice(existingEntryIndex, 1);
8.2261 - } else {
8.2262 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
8.2263 - }
8.2264 - };
8.2265 - ko.utils.registerEventHandler(element, "click", updateHandler);
8.2266 -
8.2267 - // IE 6 won't allow radio buttons to be selected unless they have a name
8.2268 - if ((element.type == "radio") && !element.name)
8.2269 - ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
8.2270 - },
8.2271 - 'update': function (element, valueAccessor) {
8.2272 - var value = ko.utils.unwrapObservable(valueAccessor());
8.2273 -
8.2274 - if (element.type == "checkbox") {
8.2275 - if (value instanceof Array) {
8.2276 - // When bound to an array, the checkbox being checked represents its value being present in that array
8.2277 - element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
8.2278 - } else {
8.2279 - // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
8.2280 - element.checked = value;
8.2281 - }
8.2282 - } else if (element.type == "radio") {
8.2283 - element.checked = (element.value == value);
8.2284 - }
8.2285 - }
8.2286 -};
8.2287 -var classesWrittenByBindingKey = '__ko__cssValue';
8.2288 -ko.bindingHandlers['css'] = {
8.2289 - 'update': function (element, valueAccessor) {
8.2290 - var value = ko.utils.unwrapObservable(valueAccessor());
8.2291 - if (typeof value == "object") {
8.2292 - for (var className in value) {
8.2293 - var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
8.2294 - ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
8.2295 - }
8.2296 - } else {
8.2297 - value = String(value || ''); // Make sure we don't try to store or set a non-string value
8.2298 - ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
8.2299 - element[classesWrittenByBindingKey] = value;
8.2300 - ko.utils.toggleDomNodeCssClass(element, value, true);
8.2301 - }
8.2302 - }
8.2303 -};
8.2304 -ko.bindingHandlers['enable'] = {
8.2305 - 'update': function (element, valueAccessor) {
8.2306 - var value = ko.utils.unwrapObservable(valueAccessor());
8.2307 - if (value && element.disabled)
8.2308 - element.removeAttribute("disabled");
8.2309 - else if ((!value) && (!element.disabled))
8.2310 - element.disabled = true;
8.2311 - }
8.2312 -};
8.2313 -
8.2314 -ko.bindingHandlers['disable'] = {
8.2315 - 'update': function (element, valueAccessor) {
8.2316 - ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
8.2317 - }
8.2318 -};
8.2319 -// For certain common events (currently just 'click'), allow a simplified data-binding syntax
8.2320 -// e.g. click:handler instead of the usual full-length event:{click:handler}
8.2321 -function makeEventHandlerShortcut(eventName) {
8.2322 - ko.bindingHandlers[eventName] = {
8.2323 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
8.2324 - var newValueAccessor = function () {
8.2325 - var result = {};
8.2326 - result[eventName] = valueAccessor();
8.2327 - return result;
8.2328 - };
8.2329 - return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
8.2330 - }
8.2331 - }
8.2332 -}
8.2333 -
8.2334 -ko.bindingHandlers['event'] = {
8.2335 - 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
8.2336 - var eventsToHandle = valueAccessor() || {};
8.2337 - for(var eventNameOutsideClosure in eventsToHandle) {
8.2338 - (function() {
8.2339 - var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
8.2340 - if (typeof eventName == "string") {
8.2341 - ko.utils.registerEventHandler(element, eventName, function (event) {
8.2342 - var handlerReturnValue;
8.2343 - var handlerFunction = valueAccessor()[eventName];
8.2344 - if (!handlerFunction)
8.2345 - return;
8.2346 - var allBindings = allBindingsAccessor();
8.2347 -
8.2348 - try {
8.2349 - // Take all the event args, and prefix with the viewmodel
8.2350 - var argsForHandler = ko.utils.makeArray(arguments);
8.2351 - argsForHandler.unshift(viewModel);
8.2352 - handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
8.2353 - } finally {
8.2354 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
8.2355 - if (event.preventDefault)
8.2356 - event.preventDefault();
8.2357 - else
8.2358 - event.returnValue = false;
8.2359 - }
8.2360 - }
8.2361 -
8.2362 - var bubble = allBindings[eventName + 'Bubble'] !== false;
8.2363 - if (!bubble) {
8.2364 - event.cancelBubble = true;
8.2365 - if (event.stopPropagation)
8.2366 - event.stopPropagation();
8.2367 - }
8.2368 - });
8.2369 - }
8.2370 - })();
8.2371 - }
8.2372 - }
8.2373 -};
8.2374 -// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
8.2375 -// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
8.2376 -ko.bindingHandlers['foreach'] = {
8.2377 - makeTemplateValueAccessor: function(valueAccessor) {
8.2378 - return function() {
8.2379 - var modelValue = valueAccessor(),
8.2380 - unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
8.2381 -
8.2382 - // If unwrappedValue is the array, pass in the wrapped value on its own
8.2383 - // The value will be unwrapped and tracked within the template binding
8.2384 - // (See https://github.com/SteveSanderson/knockout/issues/523)
8.2385 - if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
8.2386 - return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
8.2387 -
8.2388 - // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
8.2389 - ko.utils.unwrapObservable(modelValue);
8.2390 - return {
8.2391 - 'foreach': unwrappedValue['data'],
8.2392 - 'as': unwrappedValue['as'],
8.2393 - 'includeDestroyed': unwrappedValue['includeDestroyed'],
8.2394 - 'afterAdd': unwrappedValue['afterAdd'],
8.2395 - 'beforeRemove': unwrappedValue['beforeRemove'],
8.2396 - 'afterRender': unwrappedValue['afterRender'],
8.2397 - 'beforeMove': unwrappedValue['beforeMove'],
8.2398 - 'afterMove': unwrappedValue['afterMove'],
8.2399 - 'templateEngine': ko.nativeTemplateEngine.instance
8.2400 - };
8.2401 - };
8.2402 - },
8.2403 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
8.2404 - return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
8.2405 - },
8.2406 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
8.2407 - return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
8.2408 - }
8.2409 -};
8.2410 -ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
8.2411 -ko.virtualElements.allowedBindings['foreach'] = true;
8.2412 -var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
8.2413 -ko.bindingHandlers['hasfocus'] = {
8.2414 - 'init': function(element, valueAccessor, allBindingsAccessor) {
8.2415 - var handleElementFocusChange = function(isFocused) {
8.2416 - // Where possible, ignore which event was raised and determine focus state using activeElement,
8.2417 - // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
8.2418 - // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
8.2419 - // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
8.2420 - // from calling 'blur()' on the element when it loses focus.
8.2421 - // Discussion at https://github.com/SteveSanderson/knockout/pull/352
8.2422 - element[hasfocusUpdatingProperty] = true;
8.2423 - var ownerDoc = element.ownerDocument;
8.2424 - if ("activeElement" in ownerDoc) {
8.2425 - isFocused = (ownerDoc.activeElement === element);
8.2426 - }
8.2427 - var modelValue = valueAccessor();
8.2428 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
8.2429 - element[hasfocusUpdatingProperty] = false;
8.2430 - };
8.2431 - var handleElementFocusIn = handleElementFocusChange.bind(null, true);
8.2432 - var handleElementFocusOut = handleElementFocusChange.bind(null, false);
8.2433 -
8.2434 - ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
8.2435 - ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
8.2436 - ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
8.2437 - ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
8.2438 - },
8.2439 - 'update': function(element, valueAccessor) {
8.2440 - var value = ko.utils.unwrapObservable(valueAccessor());
8.2441 - if (!element[hasfocusUpdatingProperty]) {
8.2442 - value ? element.focus() : element.blur();
8.2443 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
8.2444 - }
8.2445 - }
8.2446 -};
8.2447 -ko.bindingHandlers['html'] = {
8.2448 - 'init': function() {
8.2449 - // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
8.2450 - return { 'controlsDescendantBindings': true };
8.2451 - },
8.2452 - 'update': function (element, valueAccessor) {
8.2453 - // setHtml will unwrap the value if needed
8.2454 - ko.utils.setHtml(element, valueAccessor());
8.2455 - }
8.2456 -};
8.2457 -var withIfDomDataKey = '__ko_withIfBindingData';
8.2458 -// Makes a binding like with or if
8.2459 -function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
8.2460 - ko.bindingHandlers[bindingKey] = {
8.2461 - 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
8.2462 - ko.utils.domData.set(element, withIfDomDataKey, {});
8.2463 - return { 'controlsDescendantBindings': true };
8.2464 - },
8.2465 - 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
8.2466 - var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
8.2467 - dataValue = ko.utils.unwrapObservable(valueAccessor()),
8.2468 - shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
8.2469 - isFirstRender = !withIfData.savedNodes,
8.2470 - needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
8.2471 -
8.2472 - if (needsRefresh) {
8.2473 - if (isFirstRender) {
8.2474 - withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
8.2475 - }
8.2476 -
8.2477 - if (shouldDisplay) {
8.2478 - if (!isFirstRender) {
8.2479 - ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
8.2480 - }
8.2481 - ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
8.2482 - } else {
8.2483 - ko.virtualElements.emptyNode(element);
8.2484 - }
8.2485 -
8.2486 - withIfData.didDisplayOnLastUpdate = shouldDisplay;
8.2487 - }
8.2488 - }
8.2489 - };
8.2490 - ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
8.2491 - ko.virtualElements.allowedBindings[bindingKey] = true;
8.2492 -}
8.2493 -
8.2494 -// Construct the actual binding handlers
8.2495 -makeWithIfBinding('if');
8.2496 -makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
8.2497 -makeWithIfBinding('with', true /* isWith */, false /* isNot */,
8.2498 - function(bindingContext, dataValue) {
8.2499 - return bindingContext['createChildContext'](dataValue);
8.2500 - }
8.2501 -);
8.2502 -function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
8.2503 - if (preferModelValue) {
8.2504 - if (modelValue !== ko.selectExtensions.readValue(element))
8.2505 - ko.selectExtensions.writeValue(element, modelValue);
8.2506 - }
8.2507 -
8.2508 - // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
8.2509 - // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
8.2510 - // change the model value to match the dropdown.
8.2511 - if (modelValue !== ko.selectExtensions.readValue(element))
8.2512 - ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
8.2513 -};
8.2514 -
8.2515 -ko.bindingHandlers['options'] = {
8.2516 - 'update': function (element, valueAccessor, allBindingsAccessor) {
8.2517 - if (ko.utils.tagNameLower(element) !== "select")
8.2518 - throw new Error("options binding applies only to SELECT elements");
8.2519 -
8.2520 - var selectWasPreviouslyEmpty = element.length == 0;
8.2521 - var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
8.2522 - return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
8.2523 - }), function (node) {
8.2524 - return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
8.2525 - });
8.2526 - var previousScrollTop = element.scrollTop;
8.2527 -
8.2528 - var value = ko.utils.unwrapObservable(valueAccessor());
8.2529 - var selectedValue = element.value;
8.2530 -
8.2531 - // Remove all existing <option>s.
8.2532 - // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
8.2533 - while (element.length > 0) {
8.2534 - ko.cleanNode(element.options[0]);
8.2535 - element.remove(0);
8.2536 - }
8.2537 -
8.2538 - if (value) {
8.2539 - var allBindings = allBindingsAccessor(),
8.2540 - includeDestroyed = allBindings['optionsIncludeDestroyed'];
8.2541 -
8.2542 - if (typeof value.length != "number")
8.2543 - value = [value];
8.2544 - if (allBindings['optionsCaption']) {
8.2545 - var option = document.createElement("option");
8.2546 - ko.utils.setHtml(option, allBindings['optionsCaption']);
8.2547 - ko.selectExtensions.writeValue(option, undefined);
8.2548 - element.appendChild(option);
8.2549 - }
8.2550 -
8.2551 - for (var i = 0, j = value.length; i < j; i++) {
8.2552 - // Skip destroyed items
8.2553 - var arrayEntry = value[i];
8.2554 - if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
8.2555 - continue;
8.2556 -
8.2557 - var option = document.createElement("option");
8.2558 -
8.2559 - function applyToObject(object, predicate, defaultValue) {
8.2560 - var predicateType = typeof predicate;
8.2561 - if (predicateType == "function") // Given a function; run it against the data value
8.2562 - return predicate(object);
8.2563 - else if (predicateType == "string") // Given a string; treat it as a property name on the data value
8.2564 - return object[predicate];
8.2565 - else // Given no optionsText arg; use the data value itself
8.2566 - return defaultValue;
8.2567 - }
8.2568 -
8.2569 - // Apply a value to the option element
8.2570 - var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
8.2571 - ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
8.2572 -
8.2573 - // Apply some text to the option element
8.2574 - var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
8.2575 - ko.utils.setTextContent(option, optionText);
8.2576 -
8.2577 - element.appendChild(option);
8.2578 - }
8.2579 -
8.2580 - // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
8.2581 - // That's why we first added them without selection. Now it's time to set the selection.
8.2582 - var newOptions = element.getElementsByTagName("option");
8.2583 - var countSelectionsRetained = 0;
8.2584 - for (var i = 0, j = newOptions.length; i < j; i++) {
8.2585 - if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
8.2586 - ko.utils.setOptionNodeSelectionState(newOptions[i], true);
8.2587 - countSelectionsRetained++;
8.2588 - }
8.2589 - }
8.2590 -
8.2591 - element.scrollTop = previousScrollTop;
8.2592 -
8.2593 - if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
8.2594 - // Ensure consistency between model value and selected option.
8.2595 - // If the dropdown is being populated for the first time here (or was otherwise previously empty),
8.2596 - // the dropdown selection state is meaningless, so we preserve the model value.
8.2597 - ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
8.2598 - }
8.2599 -
8.2600 - // Workaround for IE9 bug
8.2601 - ko.utils.ensureSelectElementIsRenderedCorrectly(element);
8.2602 - }
8.2603 - }
8.2604 -};
8.2605 -ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
8.2606 -ko.bindingHandlers['selectedOptions'] = {
8.2607 - 'init': function (element, valueAccessor, allBindingsAccessor) {
8.2608 - ko.utils.registerEventHandler(element, "change", function () {
8.2609 - var value = valueAccessor(), valueToWrite = [];
8.2610 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
8.2611 - if (node.selected)
8.2612 - valueToWrite.push(ko.selectExtensions.readValue(node));
8.2613 - });
8.2614 - ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
8.2615 - });
8.2616 - },
8.2617 - 'update': function (element, valueAccessor) {
8.2618 - if (ko.utils.tagNameLower(element) != "select")
8.2619 - throw new Error("values binding applies only to SELECT elements");
8.2620 -
8.2621 - var newValue = ko.utils.unwrapObservable(valueAccessor());
8.2622 - if (newValue && typeof newValue.length == "number") {
8.2623 - ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
8.2624 - var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
8.2625 - ko.utils.setOptionNodeSelectionState(node, isSelected);
8.2626 - });
8.2627 - }
8.2628 - }
8.2629 -};
8.2630 -ko.bindingHandlers['style'] = {
8.2631 - 'update': function (element, valueAccessor) {
8.2632 - var value = ko.utils.unwrapObservable(valueAccessor() || {});
8.2633 - for (var styleName in value) {
8.2634 - if (typeof styleName == "string") {
8.2635 - var styleValue = ko.utils.unwrapObservable(value[styleName]);
8.2636 - element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
8.2637 - }
8.2638 - }
8.2639 - }
8.2640 -};
8.2641 -ko.bindingHandlers['submit'] = {
8.2642 - 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
8.2643 - if (typeof valueAccessor() != "function")
8.2644 - throw new Error("The value for a submit binding must be a function");
8.2645 - ko.utils.registerEventHandler(element, "submit", function (event) {
8.2646 - var handlerReturnValue;
8.2647 - var value = valueAccessor();
8.2648 - try { handlerReturnValue = value.call(viewModel, element); }
8.2649 - finally {
8.2650 - if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
8.2651 - if (event.preventDefault)
8.2652 - event.preventDefault();
8.2653 - else
8.2654 - event.returnValue = false;
8.2655 - }
8.2656 - }
8.2657 - });
8.2658 - }
8.2659 -};
8.2660 -ko.bindingHandlers['text'] = {
8.2661 - 'update': function (element, valueAccessor) {
8.2662 - ko.utils.setTextContent(element, valueAccessor());
8.2663 - }
8.2664 -};
8.2665 -ko.virtualElements.allowedBindings['text'] = true;
8.2666 -ko.bindingHandlers['uniqueName'] = {
8.2667 - 'init': function (element, valueAccessor) {
8.2668 - if (valueAccessor()) {
8.2669 - var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
8.2670 - ko.utils.setElementName(element, name);
8.2671 - }
8.2672 - }
8.2673 -};
8.2674 -ko.bindingHandlers['uniqueName'].currentIndex = 0;
8.2675 -ko.bindingHandlers['value'] = {
8.2676 - 'init': function (element, valueAccessor, allBindingsAccessor) {
8.2677 - // Always catch "change" event; possibly other events too if asked
8.2678 - var eventsToCatch = ["change"];
8.2679 - var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
8.2680 - var propertyChangedFired = false;
8.2681 - if (requestedEventsToCatch) {
8.2682 - if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
8.2683 - requestedEventsToCatch = [requestedEventsToCatch];
8.2684 - ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
8.2685 - eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
8.2686 - }
8.2687 -
8.2688 - var valueUpdateHandler = function() {
8.2689 - propertyChangedFired = false;
8.2690 - var modelValue = valueAccessor();
8.2691 - var elementValue = ko.selectExtensions.readValue(element);
8.2692 - ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
8.2693 - }
8.2694 -
8.2695 - // Workaround for https://github.com/SteveSanderson/knockout/issues/122
8.2696 - // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
8.2697 - var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
8.2698 - && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
8.2699 - if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
8.2700 - ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
8.2701 - ko.utils.registerEventHandler(element, "blur", function() {
8.2702 - if (propertyChangedFired) {
8.2703 - valueUpdateHandler();
8.2704 - }
8.2705 - });
8.2706 - }
8.2707 -
8.2708 - ko.utils.arrayForEach(eventsToCatch, function(eventName) {
8.2709 - // The syntax "after<eventname>" means "run the handler asynchronously after the event"
8.2710 - // This is useful, for example, to catch "keydown" events after the browser has updated the control
8.2711 - // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
8.2712 - var handler = valueUpdateHandler;
8.2713 - if (ko.utils.stringStartsWith(eventName, "after")) {
8.2714 - handler = function() { setTimeout(valueUpdateHandler, 0) };
8.2715 - eventName = eventName.substring("after".length);
8.2716 - }
8.2717 - ko.utils.registerEventHandler(element, eventName, handler);
8.2718 - });
8.2719 - },
8.2720 - 'update': function (element, valueAccessor) {
8.2721 - var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
8.2722 - var newValue = ko.utils.unwrapObservable(valueAccessor());
8.2723 - var elementValue = ko.selectExtensions.readValue(element);
8.2724 - var valueHasChanged = (newValue != elementValue);
8.2725 -
8.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).
8.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.
8.2728 - if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
8.2729 - valueHasChanged = true;
8.2730 -
8.2731 - if (valueHasChanged) {
8.2732 - var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
8.2733 - applyValueAction();
8.2734 -
8.2735 - // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
8.2736 - // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
8.2737 - // to apply the value as well.
8.2738 - var alsoApplyAsynchronously = valueIsSelectOption;
8.2739 - if (alsoApplyAsynchronously)
8.2740 - setTimeout(applyValueAction, 0);
8.2741 - }
8.2742 -
8.2743 - // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
8.2744 - // because you're not allowed to have a model value that disagrees with a visible UI selection.
8.2745 - if (valueIsSelectOption && (element.length > 0))
8.2746 - ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
8.2747 - }
8.2748 -};
8.2749 -ko.bindingHandlers['visible'] = {
8.2750 - 'update': function (element, valueAccessor) {
8.2751 - var value = ko.utils.unwrapObservable(valueAccessor());
8.2752 - var isCurrentlyVisible = !(element.style.display == "none");
8.2753 - if (value && !isCurrentlyVisible)
8.2754 - element.style.display = "";
8.2755 - else if ((!value) && isCurrentlyVisible)
8.2756 - element.style.display = "none";
8.2757 - }
8.2758 -};
8.2759 -// 'click' is just a shorthand for the usual full-length event:{click:handler}
8.2760 -makeEventHandlerShortcut('click');
8.2761 -// If you want to make a custom template engine,
8.2762 -//
8.2763 -// [1] Inherit from this class (like ko.nativeTemplateEngine does)
8.2764 -// [2] Override 'renderTemplateSource', supplying a function with this signature:
8.2765 -//
8.2766 -// function (templateSource, bindingContext, options) {
8.2767 -// // - templateSource.text() is the text of the template you should render
8.2768 -// // - bindingContext.$data is the data you should pass into the template
8.2769 -// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
8.2770 -// // and bindingContext.$root available in the template too
8.2771 -// // - options gives you access to any other properties set on "data-bind: { template: options }"
8.2772 -// //
8.2773 -// // Return value: an array of DOM nodes
8.2774 -// }
8.2775 -//
8.2776 -// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
8.2777 -//
8.2778 -// function (script) {
8.2779 -// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
8.2780 -// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
8.2781 -// }
8.2782 -//
8.2783 -// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
8.2784 -// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
8.2785 -// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
8.2786 -
8.2787 -ko.templateEngine = function () { };
8.2788 -
8.2789 -ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
8.2790 - throw new Error("Override renderTemplateSource");
8.2791 -};
8.2792 -
8.2793 -ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
8.2794 - throw new Error("Override createJavaScriptEvaluatorBlock");
8.2795 -};
8.2796 -
8.2797 -ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
8.2798 - // Named template
8.2799 - if (typeof template == "string") {
8.2800 - templateDocument = templateDocument || document;
8.2801 - var elem = templateDocument.getElementById(template);
8.2802 - if (!elem)
8.2803 - throw new Error("Cannot find template with ID " + template);
8.2804 - return new ko.templateSources.domElement(elem);
8.2805 - } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
8.2806 - // Anonymous template
8.2807 - return new ko.templateSources.anonymousTemplate(template);
8.2808 - } else
8.2809 - throw new Error("Unknown template type: " + template);
8.2810 -};
8.2811 -
8.2812 -ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
8.2813 - var templateSource = this['makeTemplateSource'](template, templateDocument);
8.2814 - return this['renderTemplateSource'](templateSource, bindingContext, options);
8.2815 -};
8.2816 -
8.2817 -ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
8.2818 - // Skip rewriting if requested
8.2819 - if (this['allowTemplateRewriting'] === false)
8.2820 - return true;
8.2821 - return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
8.2822 -};
8.2823 -
8.2824 -ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
8.2825 - var templateSource = this['makeTemplateSource'](template, templateDocument);
8.2826 - var rewritten = rewriterCallback(templateSource['text']());
8.2827 - templateSource['text'](rewritten);
8.2828 - templateSource['data']("isRewritten", true);
8.2829 -};
8.2830 -
8.2831 -ko.exportSymbol('templateEngine', ko.templateEngine);
8.2832 -
8.2833 -ko.templateRewriting = (function () {
8.2834 - var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
8.2835 - var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
8.2836 -
8.2837 - function validateDataBindValuesForRewriting(keyValueArray) {
8.2838 - var allValidators = ko.expressionRewriting.bindingRewriteValidators;
8.2839 - for (var i = 0; i < keyValueArray.length; i++) {
8.2840 - var key = keyValueArray[i]['key'];
8.2841 - if (allValidators.hasOwnProperty(key)) {
8.2842 - var validator = allValidators[key];
8.2843 -
8.2844 - if (typeof validator === "function") {
8.2845 - var possibleErrorMessage = validator(keyValueArray[i]['value']);
8.2846 - if (possibleErrorMessage)
8.2847 - throw new Error(possibleErrorMessage);
8.2848 - } else if (!validator) {
8.2849 - throw new Error("This template engine does not support the '" + key + "' binding within its templates");
8.2850 - }
8.2851 - }
8.2852 - }
8.2853 - }
8.2854 -
8.2855 - function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
8.2856 - var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
8.2857 - validateDataBindValuesForRewriting(dataBindKeyValueArray);
8.2858 - var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
8.2859 -
8.2860 - // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
8.2861 - // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
8.2862 - // extra indirection.
8.2863 - var applyBindingsToNextSiblingScript =
8.2864 - "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
8.2865 - return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
8.2866 - }
8.2867 -
8.2868 - return {
8.2869 - ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
8.2870 - if (!templateEngine['isTemplateRewritten'](template, templateDocument))
8.2871 - templateEngine['rewriteTemplate'](template, function (htmlString) {
8.2872 - return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
8.2873 - }, templateDocument);
8.2874 - },
8.2875 -
8.2876 - memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
8.2877 - return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
8.2878 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
8.2879 - }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
8.2880 - return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
8.2881 - });
8.2882 - },
8.2883 -
8.2884 - applyMemoizedBindingsToNextSibling: function (bindings) {
8.2885 - return ko.memoization.memoize(function (domNode, bindingContext) {
8.2886 - if (domNode.nextSibling)
8.2887 - ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
8.2888 - });
8.2889 - }
8.2890 - }
8.2891 -})();
8.2892 -
8.2893 -
8.2894 -// Exported only because it has to be referenced by string lookup from within rewritten template
8.2895 -ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
8.2896 -(function() {
8.2897 - // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
8.2898 - // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
8.2899 - //
8.2900 - // Two are provided by default:
8.2901 - // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
8.2902 - // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
8.2903 - // without reading/writing the actual element text content, since it will be overwritten
8.2904 - // with the rendered template output.
8.2905 - // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
8.2906 - // Template sources need to have the following functions:
8.2907 - // text() - returns the template text from your storage location
8.2908 - // text(value) - writes the supplied template text to your storage location
8.2909 - // data(key) - reads values stored using data(key, value) - see below
8.2910 - // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
8.2911 - //
8.2912 - // Optionally, template sources can also have the following functions:
8.2913 - // nodes() - returns a DOM element containing the nodes of this template, where available
8.2914 - // nodes(value) - writes the given DOM element to your storage location
8.2915 - // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
8.2916 - // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
8.2917 - //
8.2918 - // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
8.2919 - // using and overriding "makeTemplateSource" to return an instance of your custom template source.
8.2920 -
8.2921 - ko.templateSources = {};
8.2922 -
8.2923 - // ---- ko.templateSources.domElement -----
8.2924 -
8.2925 - ko.templateSources.domElement = function(element) {
8.2926 - this.domElement = element;
8.2927 - }
8.2928 -
8.2929 - ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
8.2930 - var tagNameLower = ko.utils.tagNameLower(this.domElement),
8.2931 - elemContentsProperty = tagNameLower === "script" ? "text"
8.2932 - : tagNameLower === "textarea" ? "value"
8.2933 - : "innerHTML";
8.2934 -
8.2935 - if (arguments.length == 0) {
8.2936 - return this.domElement[elemContentsProperty];
8.2937 - } else {
8.2938 - var valueToWrite = arguments[0];
8.2939 - if (elemContentsProperty === "innerHTML")
8.2940 - ko.utils.setHtml(this.domElement, valueToWrite);
8.2941 - else
8.2942 - this.domElement[elemContentsProperty] = valueToWrite;
8.2943 - }
8.2944 - };
8.2945 -
8.2946 - ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
8.2947 - if (arguments.length === 1) {
8.2948 - return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
8.2949 - } else {
8.2950 - ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
8.2951 - }
8.2952 - };
8.2953 -
8.2954 - // ---- ko.templateSources.anonymousTemplate -----
8.2955 - // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
8.2956 - // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
8.2957 - // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
8.2958 -
8.2959 - var anonymousTemplatesDomDataKey = "__ko_anon_template__";
8.2960 - ko.templateSources.anonymousTemplate = function(element) {
8.2961 - this.domElement = element;
8.2962 - }
8.2963 - ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
8.2964 - ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
8.2965 - if (arguments.length == 0) {
8.2966 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
8.2967 - if (templateData.textData === undefined && templateData.containerData)
8.2968 - templateData.textData = templateData.containerData.innerHTML;
8.2969 - return templateData.textData;
8.2970 - } else {
8.2971 - var valueToWrite = arguments[0];
8.2972 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
8.2973 - }
8.2974 - };
8.2975 - ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
8.2976 - if (arguments.length == 0) {
8.2977 - var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
8.2978 - return templateData.containerData;
8.2979 - } else {
8.2980 - var valueToWrite = arguments[0];
8.2981 - ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
8.2982 - }
8.2983 - };
8.2984 -
8.2985 - ko.exportSymbol('templateSources', ko.templateSources);
8.2986 - ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
8.2987 - ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
8.2988 -})();
8.2989 -(function () {
8.2990 - var _templateEngine;
8.2991 - ko.setTemplateEngine = function (templateEngine) {
8.2992 - if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
8.2993 - throw new Error("templateEngine must inherit from ko.templateEngine");
8.2994 - _templateEngine = templateEngine;
8.2995 - }
8.2996 -
8.2997 - function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
8.2998 - var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
8.2999 - while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
8.3000 - nextInQueue = ko.virtualElements.nextSibling(node);
8.3001 - if (node.nodeType === 1 || node.nodeType === 8)
8.3002 - action(node);
8.3003 - }
8.3004 - }
8.3005 -
8.3006 - function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
8.3007 - // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
8.3008 - // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
8.3009 - // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
8.3010 - // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
8.3011 - // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
8.3012 -
8.3013 - if (continuousNodeArray.length) {
8.3014 - var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
8.3015 -
8.3016 - // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
8.3017 - // whereas a regular applyBindings won't introduce new memoized nodes
8.3018 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
8.3019 - ko.applyBindings(bindingContext, node);
8.3020 - });
8.3021 - invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
8.3022 - ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
8.3023 - });
8.3024 - }
8.3025 - }
8.3026 -
8.3027 - function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
8.3028 - return nodeOrNodeArray.nodeType ? nodeOrNodeArray
8.3029 - : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
8.3030 - : null;
8.3031 - }
8.3032 -
8.3033 - function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
8.3034 - options = options || {};
8.3035 - var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
8.3036 - var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
8.3037 - var templateEngineToUse = (options['templateEngine'] || _templateEngine);
8.3038 - ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
8.3039 - var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
8.3040 -
8.3041 - // Loosely check result is an array of DOM nodes
8.3042 - if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
8.3043 - throw new Error("Template engine must return an array of DOM nodes");
8.3044 -
8.3045 - var haveAddedNodesToParent = false;
8.3046 - switch (renderMode) {
8.3047 - case "replaceChildren":
8.3048 - ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
8.3049 - haveAddedNodesToParent = true;
8.3050 - break;
8.3051 - case "replaceNode":
8.3052 - ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
8.3053 - haveAddedNodesToParent = true;
8.3054 - break;
8.3055 - case "ignoreTargetNode": break;
8.3056 - default:
8.3057 - throw new Error("Unknown renderMode: " + renderMode);
8.3058 - }
8.3059 -
8.3060 - if (haveAddedNodesToParent) {
8.3061 - activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
8.3062 - if (options['afterRender'])
8.3063 - ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
8.3064 - }
8.3065 -
8.3066 - return renderedNodesArray;
8.3067 - }
8.3068 -
8.3069 - ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
8.3070 - options = options || {};
8.3071 - if ((options['templateEngine'] || _templateEngine) == undefined)
8.3072 - throw new Error("Set a template engine before calling renderTemplate");
8.3073 - renderMode = renderMode || "replaceChildren";
8.3074 -
8.3075 - if (targetNodeOrNodeArray) {
8.3076 - var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
8.3077 -
8.3078 - var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
8.3079 - var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
8.3080 -
8.3081 - return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
8.3082 - function () {
8.3083 - // Ensure we've got a proper binding context to work with
8.3084 - var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
8.3085 - ? dataOrBindingContext
8.3086 - : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
8.3087 -
8.3088 - // Support selecting template as a function of the data being rendered
8.3089 - var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
8.3090 -
8.3091 - var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
8.3092 - if (renderMode == "replaceNode") {
8.3093 - targetNodeOrNodeArray = renderedNodesArray;
8.3094 - firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
8.3095 - }
8.3096 - },
8.3097 - null,
8.3098 - { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
8.3099 - );
8.3100 - } else {
8.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
8.3102 - return ko.memoization.memoize(function (domNode) {
8.3103 - ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
8.3104 - });
8.3105 - }
8.3106 - };
8.3107 -
8.3108 - ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
8.3109 - // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
8.3110 - // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
8.3111 - var arrayItemContext;
8.3112 -
8.3113 - // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
8.3114 - var executeTemplateForArrayItem = function (arrayValue, index) {
8.3115 - // Support selecting template as a function of the data being rendered
8.3116 - arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
8.3117 - arrayItemContext['$index'] = index;
8.3118 - var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
8.3119 - return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
8.3120 - }
8.3121 -
8.3122 - // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
8.3123 - var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
8.3124 - activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
8.3125 - if (options['afterRender'])
8.3126 - options['afterRender'](addedNodesArray, arrayValue);
8.3127 - };
8.3128 -
8.3129 - return ko.dependentObservable(function () {
8.3130 - var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
8.3131 - if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
8.3132 - unwrappedArray = [unwrappedArray];
8.3133 -
8.3134 - // Filter out any entries marked as destroyed
8.3135 - var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
8.3136 - return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
8.3137 - });
8.3138 -
8.3139 - // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
8.3140 - // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
8.3141 - ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
8.3142 -
8.3143 - }, null, { disposeWhenNodeIsRemoved: targetNode });
8.3144 - };
8.3145 -
8.3146 - var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
8.3147 - function disposeOldComputedAndStoreNewOne(element, newComputed) {
8.3148 - var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
8.3149 - if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
8.3150 - oldComputed.dispose();
8.3151 - ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
8.3152 - }
8.3153 -
8.3154 - ko.bindingHandlers['template'] = {
8.3155 - 'init': function(element, valueAccessor) {
8.3156 - // Support anonymous templates
8.3157 - var bindingValue = ko.utils.unwrapObservable(valueAccessor());
8.3158 - if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
8.3159 - // It's an anonymous template - store the element contents, then clear the element
8.3160 - var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
8.3161 - container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
8.3162 - new ko.templateSources.anonymousTemplate(element)['nodes'](container);
8.3163 - }
8.3164 - return { 'controlsDescendantBindings': true };
8.3165 - },
8.3166 - 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
8.3167 - var templateName = ko.utils.unwrapObservable(valueAccessor()),
8.3168 - options = {},
8.3169 - shouldDisplay = true,
8.3170 - dataValue,
8.3171 - templateComputed = null;
8.3172 -
8.3173 - if (typeof templateName != "string") {
8.3174 - options = templateName;
8.3175 - templateName = options['name'];
8.3176 -
8.3177 - // Support "if"/"ifnot" conditions
8.3178 - if ('if' in options)
8.3179 - shouldDisplay = ko.utils.unwrapObservable(options['if']);
8.3180 - if (shouldDisplay && 'ifnot' in options)
8.3181 - shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
8.3182 -
8.3183 - dataValue = ko.utils.unwrapObservable(options['data']);
8.3184 - }
8.3185 -
8.3186 - if ('foreach' in options) {
8.3187 - // Render once for each data point (treating data set as empty if shouldDisplay==false)
8.3188 - var dataArray = (shouldDisplay && options['foreach']) || [];
8.3189 - templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
8.3190 - } else if (!shouldDisplay) {
8.3191 - ko.virtualElements.emptyNode(element);
8.3192 - } else {
8.3193 - // Render once for this single data point (or use the viewModel if no data was provided)
8.3194 - var innerBindingContext = ('data' in options) ?
8.3195 - bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
8.3196 - bindingContext; // Given no explicit 'data' value, we retain the same binding context
8.3197 - templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
8.3198 - }
8.3199 -
8.3200 - // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
8.3201 - disposeOldComputedAndStoreNewOne(element, templateComputed);
8.3202 - }
8.3203 - };
8.3204 -
8.3205 - // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
8.3206 - ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
8.3207 - var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
8.3208 -
8.3209 - if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
8.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)
8.3211 -
8.3212 - if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
8.3213 - return null; // Named templates can be rewritten, so return "no error"
8.3214 - return "This template engine does not support anonymous templates nested within its templates";
8.3215 - };
8.3216 -
8.3217 - ko.virtualElements.allowedBindings['template'] = true;
8.3218 -})();
8.3219 -
8.3220 -ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
8.3221 -ko.exportSymbol('renderTemplate', ko.renderTemplate);
8.3222 -
8.3223 -ko.utils.compareArrays = (function () {
8.3224 - var statusNotInOld = 'added', statusNotInNew = 'deleted';
8.3225 -
8.3226 - // Simple calculation based on Levenshtein distance.
8.3227 - function compareArrays(oldArray, newArray, dontLimitMoves) {
8.3228 - oldArray = oldArray || [];
8.3229 - newArray = newArray || [];
8.3230 -
8.3231 - if (oldArray.length <= newArray.length)
8.3232 - return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
8.3233 - else
8.3234 - return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
8.3235 - }
8.3236 -
8.3237 - function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
8.3238 - var myMin = Math.min,
8.3239 - myMax = Math.max,
8.3240 - editDistanceMatrix = [],
8.3241 - smlIndex, smlIndexMax = smlArray.length,
8.3242 - bigIndex, bigIndexMax = bigArray.length,
8.3243 - compareRange = (bigIndexMax - smlIndexMax) || 1,
8.3244 - maxDistance = smlIndexMax + bigIndexMax + 1,
8.3245 - thisRow, lastRow,
8.3246 - bigIndexMaxForRow, bigIndexMinForRow;
8.3247 -
8.3248 - for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
8.3249 - lastRow = thisRow;
8.3250 - editDistanceMatrix.push(thisRow = []);
8.3251 - bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
8.3252 - bigIndexMinForRow = myMax(0, smlIndex - 1);
8.3253 - for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
8.3254 - if (!bigIndex)
8.3255 - thisRow[bigIndex] = smlIndex + 1;
8.3256 - else if (!smlIndex) // Top row - transform empty array into new array via additions
8.3257 - thisRow[bigIndex] = bigIndex + 1;
8.3258 - else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
8.3259 - thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
8.3260 - else {
8.3261 - var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
8.3262 - var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
8.3263 - thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
8.3264 - }
8.3265 - }
8.3266 - }
8.3267 -
8.3268 - var editScript = [], meMinusOne, notInSml = [], notInBig = [];
8.3269 - for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
8.3270 - meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
8.3271 - if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
8.3272 - notInSml.push(editScript[editScript.length] = { // added
8.3273 - 'status': statusNotInSml,
8.3274 - 'value': bigArray[--bigIndex],
8.3275 - 'index': bigIndex });
8.3276 - } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
8.3277 - notInBig.push(editScript[editScript.length] = { // deleted
8.3278 - 'status': statusNotInBig,
8.3279 - 'value': smlArray[--smlIndex],
8.3280 - 'index': smlIndex });
8.3281 - } else {
8.3282 - editScript.push({
8.3283 - 'status': "retained",
8.3284 - 'value': bigArray[--bigIndex] });
8.3285 - --smlIndex;
8.3286 - }
8.3287 - }
8.3288 -
8.3289 - if (notInSml.length && notInBig.length) {
8.3290 - // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
8.3291 - // smlIndexMax keeps the time complexity of this algorithm linear.
8.3292 - var limitFailedCompares = smlIndexMax * 10, failedCompares,
8.3293 - a, d, notInSmlItem, notInBigItem;
8.3294 - // Go through the items that have been added and deleted and try to find matches between them.
8.3295 - for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
8.3296 - for (d = 0; notInBigItem = notInBig[d]; d++) {
8.3297 - if (notInSmlItem['value'] === notInBigItem['value']) {
8.3298 - notInSmlItem['moved'] = notInBigItem['index'];
8.3299 - notInBigItem['moved'] = notInSmlItem['index'];
8.3300 - notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
8.3301 - failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
8.3302 - break;
8.3303 - }
8.3304 - }
8.3305 - failedCompares += d;
8.3306 - }
8.3307 - }
8.3308 - return editScript.reverse();
8.3309 - }
8.3310 -
8.3311 - return compareArrays;
8.3312 -})();
8.3313 -
8.3314 -ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
8.3315 -
8.3316 -(function () {
8.3317 - // Objective:
8.3318 - // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
8.3319 - // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
8.3320 - // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
8.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
8.3322 - // previously mapped - retain those nodes, and just insert/delete other ones
8.3323 -
8.3324 - // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
8.3325 - // You can use this, for example, to activate bindings on those nodes.
8.3326 -
8.3327 - function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
8.3328 - // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
8.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,
8.3330 - // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
8.3331 - // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
8.3332 - // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
8.3333 - //
8.3334 - // Rules:
8.3335 - // [A] Any leading nodes that aren't in the document any more should be ignored
8.3336 - // These most likely correspond to memoization nodes that were already removed during binding
8.3337 - // See https://github.com/SteveSanderson/knockout/pull/440
8.3338 - // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
8.3339 - // have already been removed, and include any nodes that have been inserted among the previous collection
8.3340 -
8.3341 - // Rule [A]
8.3342 - while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
8.3343 - contiguousNodeArray.splice(0, 1);
8.3344 -
8.3345 - // Rule [B]
8.3346 - if (contiguousNodeArray.length > 1) {
8.3347 - // Build up the actual new contiguous node set
8.3348 - var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
8.3349 - while (current !== last) {
8.3350 - current = current.nextSibling;
8.3351 - if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
8.3352 - return;
8.3353 - newContiguousSet.push(current);
8.3354 - }
8.3355 -
8.3356 - // ... then mutate the input array to match this.
8.3357 - // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
8.3358 - Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
8.3359 - }
8.3360 - return contiguousNodeArray;
8.3361 - }
8.3362 -
8.3363 - function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
8.3364 - // Map this array value inside a dependentObservable so we re-map when any dependency changes
8.3365 - var mappedNodes = [];
8.3366 - var dependentObservable = ko.dependentObservable(function() {
8.3367 - var newMappedNodes = mapping(valueToMap, index) || [];
8.3368 -
8.3369 - // On subsequent evaluations, just replace the previously-inserted DOM nodes
8.3370 - if (mappedNodes.length > 0) {
8.3371 - ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
8.3372 - if (callbackAfterAddingNodes)
8.3373 - ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
8.3374 - }
8.3375 -
8.3376 - // Replace the contents of the mappedNodes array, thereby updating the record
8.3377 - // of which nodes would be deleted if valueToMap was itself later removed
8.3378 - mappedNodes.splice(0, mappedNodes.length);
8.3379 - ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
8.3380 - }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
8.3381 - return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
8.3382 - }
8.3383 -
8.3384 - var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
8.3385 -
8.3386 - ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
8.3387 - // Compare the provided array against the previous one
8.3388 - array = array || [];
8.3389 - options = options || {};
8.3390 - var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
8.3391 - var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
8.3392 - var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
8.3393 - var editScript = ko.utils.compareArrays(lastArray, array);
8.3394 -
8.3395 - // Build the new mapping result
8.3396 - var newMappingResult = [];
8.3397 - var lastMappingResultIndex = 0;
8.3398 - var newMappingResultIndex = 0;
8.3399 -
8.3400 - var nodesToDelete = [];
8.3401 - var itemsToProcess = [];
8.3402 - var itemsForBeforeRemoveCallbacks = [];
8.3403 - var itemsForMoveCallbacks = [];
8.3404 - var itemsForAfterAddCallbacks = [];
8.3405 - var mapData;
8.3406 -
8.3407 - function itemMovedOrRetained(editScriptIndex, oldPosition) {
8.3408 - mapData = lastMappingResult[oldPosition];
8.3409 - if (newMappingResultIndex !== oldPosition)
8.3410 - itemsForMoveCallbacks[editScriptIndex] = mapData;
8.3411 - // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
8.3412 - mapData.indexObservable(newMappingResultIndex++);
8.3413 - fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
8.3414 - newMappingResult.push(mapData);
8.3415 - itemsToProcess.push(mapData);
8.3416 - }
8.3417 -
8.3418 - function callCallback(callback, items) {
8.3419 - if (callback) {
8.3420 - for (var i = 0, n = items.length; i < n; i++) {
8.3421 - if (items[i]) {
8.3422 - ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
8.3423 - callback(node, i, items[i].arrayEntry);
8.3424 - });
8.3425 - }
8.3426 - }
8.3427 - }
8.3428 - }
8.3429 -
8.3430 - for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
8.3431 - movedIndex = editScriptItem['moved'];
8.3432 - switch (editScriptItem['status']) {
8.3433 - case "deleted":
8.3434 - if (movedIndex === undefined) {
8.3435 - mapData = lastMappingResult[lastMappingResultIndex];
8.3436 -
8.3437 - // Stop tracking changes to the mapping for these nodes
8.3438 - if (mapData.dependentObservable)
8.3439 - mapData.dependentObservable.dispose();
8.3440 -
8.3441 - // Queue these nodes for later removal
8.3442 - nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
8.3443 - if (options['beforeRemove']) {
8.3444 - itemsForBeforeRemoveCallbacks[i] = mapData;
8.3445 - itemsToProcess.push(mapData);
8.3446 - }
8.3447 - }
8.3448 - lastMappingResultIndex++;
8.3449 - break;
8.3450 -
8.3451 - case "retained":
8.3452 - itemMovedOrRetained(i, lastMappingResultIndex++);
8.3453 - break;
8.3454 -
8.3455 - case "added":
8.3456 - if (movedIndex !== undefined) {
8.3457 - itemMovedOrRetained(i, movedIndex);
8.3458 - } else {
8.3459 - mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
8.3460 - newMappingResult.push(mapData);
8.3461 - itemsToProcess.push(mapData);
8.3462 - if (!isFirstExecution)
8.3463 - itemsForAfterAddCallbacks[i] = mapData;
8.3464 - }
8.3465 - break;
8.3466 - }
8.3467 - }
8.3468 -
8.3469 - // Call beforeMove first before any changes have been made to the DOM
8.3470 - callCallback(options['beforeMove'], itemsForMoveCallbacks);
8.3471 -
8.3472 - // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
8.3473 - ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
8.3474 -
8.3475 - // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
8.3476 - for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
8.3477 - // Get nodes for newly added items
8.3478 - if (!mapData.mappedNodes)
8.3479 - ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
8.3480 -
8.3481 - // Put nodes in the right place if they aren't there already
8.3482 - for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
8.3483 - if (node !== nextNode)
8.3484 - ko.virtualElements.insertAfter(domNode, node, lastNode);
8.3485 - }
8.3486 -
8.3487 - // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
8.3488 - if (!mapData.initialized && callbackAfterAddingNodes) {
8.3489 - callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
8.3490 - mapData.initialized = true;
8.3491 - }
8.3492 - }
8.3493 -
8.3494 - // If there's a beforeRemove callback, call it after reordering.
8.3495 - // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
8.3496 - // some sort of animation, which is why we first reorder the nodes that will be removed. If the
8.3497 - // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
8.3498 - // Perhaps we'll make that change in the future if this scenario becomes more common.
8.3499 - callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
8.3500 -
8.3501 - // Finally call afterMove and afterAdd callbacks
8.3502 - callCallback(options['afterMove'], itemsForMoveCallbacks);
8.3503 - callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
8.3504 -
8.3505 - // Store a copy of the array items we just considered so we can difference it next time
8.3506 - ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
8.3507 - }
8.3508 -})();
8.3509 -
8.3510 -ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
8.3511 -ko.nativeTemplateEngine = function () {
8.3512 - this['allowTemplateRewriting'] = false;
8.3513 -}
8.3514 -
8.3515 -ko.nativeTemplateEngine.prototype = new ko.templateEngine();
8.3516 -ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
8.3517 - var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
8.3518 - templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
8.3519 - templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
8.3520 -
8.3521 - if (templateNodes) {
8.3522 - return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
8.3523 - } else {
8.3524 - var templateText = templateSource['text']();
8.3525 - return ko.utils.parseHtmlFragment(templateText);
8.3526 - }
8.3527 -};
8.3528 -
8.3529 -ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
8.3530 -ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
8.3531 -
8.3532 -ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
8.3533 -(function() {
8.3534 - ko.jqueryTmplTemplateEngine = function () {
8.3535 - // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
8.3536 - // doesn't expose a version number, so we have to infer it.
8.3537 - // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
8.3538 - // which KO internally refers to as version "2", so older versions are no longer detected.
8.3539 - var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
8.3540 - if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
8.3541 - return 0;
8.3542 - // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
8.3543 - try {
8.3544 - if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
8.3545 - // Since 1.0.0pre, custom tags should append markup to an array called "__"
8.3546 - return 2; // Final version of jquery.tmpl
8.3547 - }
8.3548 - } catch(ex) { /* Apparently not the version we were looking for */ }
8.3549 -
8.3550 - return 1; // Any older version that we don't support
8.3551 - })();
8.3552 -
8.3553 - function ensureHasReferencedJQueryTemplates() {
8.3554 - if (jQueryTmplVersion < 2)
8.3555 - throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
8.3556 - }
8.3557 -
8.3558 - function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
8.3559 - return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
8.3560 - }
8.3561 -
8.3562 - this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
8.3563 - options = options || {};
8.3564 - ensureHasReferencedJQueryTemplates();
8.3565 -
8.3566 - // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
8.3567 - var precompiled = templateSource['data']('precompiled');
8.3568 - if (!precompiled) {
8.3569 - var templateText = templateSource['text']() || "";
8.3570 - // Wrap in "with($whatever.koBindingContext) { ... }"
8.3571 - templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
8.3572 -
8.3573 - precompiled = jQuery['template'](null, templateText);
8.3574 - templateSource['data']('precompiled', precompiled);
8.3575 - }
8.3576 -
8.3577 - var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
8.3578 - var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
8.3579 -
8.3580 - var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
8.3581 - resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
8.3582 -
8.3583 - jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
8.3584 - return resultNodes;
8.3585 - };
8.3586 -
8.3587 - this['createJavaScriptEvaluatorBlock'] = function(script) {
8.3588 - return "{{ko_code ((function() { return " + script + " })()) }}";
8.3589 - };
8.3590 -
8.3591 - this['addTemplate'] = function(templateName, templateMarkup) {
8.3592 - document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
8.3593 - };
8.3594 -
8.3595 - if (jQueryTmplVersion > 0) {
8.3596 - jQuery['tmpl']['tag']['ko_code'] = {
8.3597 - open: "__.push($1 || '');"
8.3598 - };
8.3599 - jQuery['tmpl']['tag']['ko_with'] = {
8.3600 - open: "with($1) {",
8.3601 - close: "} "
8.3602 - };
8.3603 - }
8.3604 - };
8.3605 -
8.3606 - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
8.3607 -
8.3608 - // Use this one by default *only if jquery.tmpl is referenced*
8.3609 - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
8.3610 - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
8.3611 - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
8.3612 -
8.3613 - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
8.3614 -})();
8.3615 -});
8.3616 -})(window,document,navigator,window["jQuery"]);
8.3617 -})();
8.3618 \ No newline at end of file
9.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
9.2 +++ b/ko/bck2brwsr/src/test/java/org/apidesign/bck2brwsr/ko2brwsr/Bck2BrwsrJavaScriptBodyTest.java Mon Jan 13 12:37:03 2014 +0100
9.3 @@ -0,0 +1,34 @@
9.4 +/**
9.5 + * Back 2 Browser Bytecode Translator
9.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
9.7 + *
9.8 + * This program is free software: you can redistribute it and/or modify
9.9 + * it under the terms of the GNU General Public License as published by
9.10 + * the Free Software Foundation, version 2 of the License.
9.11 + *
9.12 + * This program is distributed in the hope that it will be useful,
9.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
9.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9.15 + * GNU General Public License for more details.
9.16 + *
9.17 + * You should have received a copy of the GNU General Public License
9.18 + * along with this program. Look for COPYING file in the top folder.
9.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
9.20 + */
9.21 +package org.apidesign.bck2brwsr.ko2brwsr;
9.22 +
9.23 +import org.apidesign.bck2brwsr.vmtest.VMTest;
9.24 +import org.apidesign.html.json.tck.JavaScriptTCK;
9.25 +import org.apidesign.html.json.tck.KOTest;
9.26 +import org.testng.annotations.Factory;
9.27 +
9.28 +/**
9.29 + *
9.30 + * @author Jaroslav Tulach <jtulach@netbeans.org>
9.31 + */
9.32 +public class Bck2BrwsrJavaScriptBodyTest extends JavaScriptTCK {
9.33 + @Factory public static Object[] tests() {
9.34 + return VMTest.newTests().withClasses(testClasses())
9.35 + .withTestAnnotation(KOTest.class).build();
9.36 + }
9.37 +}
10.1 --- a/ko/bck2brwsr/src/test/java/org/apidesign/bck2brwsr/ko2brwsr/Bck2BrwsrKnockoutTest.java Wed Dec 11 08:22:17 2013 +0100
10.2 +++ b/ko/bck2brwsr/src/test/java/org/apidesign/bck2brwsr/ko2brwsr/Bck2BrwsrKnockoutTest.java Mon Jan 13 12:37:03 2014 +0100
10.3 @@ -31,6 +31,7 @@
10.4 import org.apidesign.html.json.spi.WSTransfer;
10.5 import org.apidesign.html.json.tck.KOTest;
10.6 import org.apidesign.html.json.tck.KnockoutTCK;
10.7 +import org.netbeans.html.ko4j.KO4J;
10.8 import org.openide.util.lookup.ServiceProvider;
10.9 import org.testng.annotations.Factory;
10.10
10.11 @@ -50,10 +51,11 @@
10.12
10.13 @Override
10.14 public BrwsrCtx createContext() {
10.15 + KO4J ko = new KO4J(null);
10.16 return Contexts.newBuilder().
10.17 - register(Transfer.class, BrwsrCtxImpl.DEFAULT, 9).
10.18 - register(WSTransfer.class, BrwsrCtxImpl.DEFAULT, 9).
10.19 - register(Technology.class, BrwsrCtxImpl.DEFAULT, 9).build();
10.20 + register(Transfer.class, ko.transfer(), 9).
10.21 + register(WSTransfer.class, ko.websockets(), 9).
10.22 + register(Technology.class, ko.knockout(), 9).build();
10.23 }
10.24
10.25
11.1 --- a/ko/fx/pom.xml Wed Dec 11 08:22:17 2013 +0100
11.2 +++ b/ko/fx/pom.xml Mon Jan 13 12:37:03 2014 +0100
11.3 @@ -40,7 +40,7 @@
11.4 <type>jar</type>
11.5 </dependency>
11.6 <dependency>
11.7 - <groupId>org.apidesign.html</groupId>
11.8 + <groupId>org.netbeans.html</groupId>
11.9 <artifactId>net.java.html.json</artifactId>
11.10 <version>${net.java.html.version}</version>
11.11 </dependency>
11.12 @@ -50,7 +50,7 @@
11.13 <scope>test</scope>
11.14 </dependency>
11.15 <dependency>
11.16 - <groupId>org.apidesign.html</groupId>
11.17 + <groupId>org.netbeans.html</groupId>
11.18 <artifactId>net.java.html.json.tck</artifactId>
11.19 <version>${net.java.html.version}</version>
11.20 <scope>test</scope>
11.21 @@ -67,14 +67,14 @@
11.22 <scope>test</scope>
11.23 </dependency>
11.24 <dependency>
11.25 - <groupId>org.apidesign.html</groupId>
11.26 + <groupId>org.netbeans.html</groupId>
11.27 <artifactId>net.java.html.boot</artifactId>
11.28 <version>${net.java.html.version}</version>
11.29 <type>jar</type>
11.30 </dependency>
11.31 <dependency>
11.32 - <groupId>org.apidesign.html</groupId>
11.33 - <artifactId>ko-fx</artifactId>
11.34 + <groupId>org.netbeans.html</groupId>
11.35 + <artifactId>ko4j</artifactId>
11.36 <version>${net.java.html.version}</version>
11.37 <type>jar</type>
11.38 </dependency>
11.39 @@ -86,7 +86,7 @@
11.40 <type>jar</type>
11.41 </dependency>
11.42 <dependency>
11.43 - <groupId>org.apidesign.html</groupId>
11.44 + <groupId>org.netbeans.html</groupId>
11.45 <artifactId>ko-ws-tyrus</artifactId>
11.46 <version>${net.java.html.version}</version>
11.47 <scope>test</scope>
12.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
12.2 +++ b/ko/fx/src/test/java/org/apidesign/bck2brwsr/kofx/JavaScriptBodyFXBrwsrTest.java Mon Jan 13 12:37:03 2014 +0100
12.3 @@ -0,0 +1,36 @@
12.4 +/**
12.5 + * Back 2 Browser Bytecode Translator
12.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
12.7 + *
12.8 + * This program is free software: you can redistribute it and/or modify
12.9 + * it under the terms of the GNU General Public License as published by
12.10 + * the Free Software Foundation, version 2 of the License.
12.11 + *
12.12 + * This program is distributed in the hope that it will be useful,
12.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
12.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12.15 + * GNU General Public License for more details.
12.16 + *
12.17 + * You should have received a copy of the GNU General Public License
12.18 + * along with this program. Look for COPYING file in the top folder.
12.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
12.20 + */
12.21 +package org.apidesign.bck2brwsr.kofx;
12.22 +
12.23 +import org.apidesign.bck2brwsr.vmtest.VMTest;
12.24 +import org.apidesign.html.json.tck.JavaScriptTCK;
12.25 +import org.apidesign.html.json.tck.KOTest;
12.26 +import org.testng.annotations.Factory;
12.27 +
12.28 +/**
12.29 + *
12.30 + * @author Jaroslav Tulach <jtulach@netbeans.org>
12.31 + */
12.32 +public class JavaScriptBodyFXBrwsrTest extends JavaScriptTCK {
12.33 + @Factory public static Object[] create() {
12.34 + return VMTest.newTests().
12.35 + withLaunchers("fxbrwsr").
12.36 + withClasses(testClasses()).
12.37 + withTestAnnotation(KOTest.class).build();
12.38 + }
12.39 +}
13.1 --- a/ko/fx/src/test/java/org/apidesign/bck2brwsr/kofx/KnockoutFXTest.java Wed Dec 11 08:22:17 2013 +0100
13.2 +++ b/ko/fx/src/test/java/org/apidesign/bck2brwsr/kofx/KnockoutFXTest.java Mon Jan 13 12:37:03 2014 +0100
13.3 @@ -28,17 +28,17 @@
13.4 import net.java.html.BrwsrCtx;
13.5 import net.java.html.js.JavaScriptBody;
13.6 import org.apidesign.bck2brwsr.vmtest.VMTest;
13.7 -import org.apidesign.html.boot.impl.FnUtils;
13.8 +import org.apidesign.html.boot.spi.Fn;
13.9 import org.apidesign.html.context.spi.Contexts;
13.10 import org.apidesign.html.json.spi.Technology;
13.11 import org.apidesign.html.json.spi.Transfer;
13.12 import org.apidesign.html.json.spi.WSTransfer;
13.13 import org.apidesign.html.json.tck.KOTest;
13.14 import org.apidesign.html.json.tck.KnockoutTCK;
13.15 -import org.apidesign.html.kofx.FXContext;
13.16 -import org.apidesign.html.wstyrus.TyrusContext;
13.17 import org.json.JSONException;
13.18 import org.json.JSONObject;
13.19 +import org.netbeans.html.ko4j.KO4J;
13.20 +import org.netbeans.html.wstyrus.TyrusContext;
13.21 import org.openide.util.lookup.ServiceProvider;
13.22 import org.testng.annotations.Factory;
13.23
13.24 @@ -60,34 +60,36 @@
13.25
13.26 @Override
13.27 public BrwsrCtx createContext() {
13.28 - FXContext fx = new FXContext(FnUtils.currentPresenter());
13.29 + KO4J ko = new KO4J(Fn.activePresenter());
13.30 TyrusContext tc = new TyrusContext();
13.31 Contexts.Builder b = Contexts.newBuilder().
13.32 - register(Technology.class, fx, 10).
13.33 - register(Transfer.class, fx, 10);
13.34 + register(Technology.class, ko.knockout(), 10).
13.35 + register(Transfer.class, ko.transfer(), 10);
13.36 try {
13.37 Class.forName("java.util.function.Function");
13.38 // prefer WebView's WebSockets on JDK8
13.39 - b.register(WSTransfer.class, fx, 10);
13.40 + b.register(WSTransfer.class, ko.websockets(), 10);
13.41 } catch (ClassNotFoundException ex) {
13.42 // ok, JDK7 needs tyrus
13.43 b.register(WSTransfer.class, tc, 20);
13.44 + b.register(Transfer.class, tc, 5);
13.45 }
13.46 return b.build();
13.47 }
13.48
13.49 @Override
13.50 public Object createJSON(Map<String, Object> values) {
13.51 - JSONObject json = new JSONObject();
13.52 + Object json = createJSON();
13.53 for (Map.Entry<String, Object> entry : values.entrySet()) {
13.54 - try {
13.55 - json.put(entry.getKey(), entry.getValue());
13.56 - } catch (JSONException ex) {
13.57 - throw new IllegalStateException(ex);
13.58 - }
13.59 + setProperty(json, entry.getKey(), entry.getValue());
13.60 }
13.61 return json;
13.62 }
13.63 +
13.64 + @JavaScriptBody(args = {}, body = "return new Object();")
13.65 + private static native Object createJSON();
13.66 + @JavaScriptBody(args = { "json", "key", "value" }, body = "json[key] = value;")
13.67 + private static native void setProperty(Object json, String key, Object value);
13.68
13.69 @Override
13.70 @JavaScriptBody(args = { "s", "args" }, body = ""
14.1 --- a/launcher/fx/pom.xml Wed Dec 11 08:22:17 2013 +0100
14.2 +++ b/launcher/fx/pom.xml Mon Jan 13 12:37:03 2014 +0100
14.3 @@ -75,7 +75,7 @@
14.4 <version>4.1</version>
14.5 </dependency>
14.6 <dependency>
14.7 - <groupId>org.apidesign.html</groupId>
14.8 + <groupId>org.netbeans.html</groupId>
14.9 <artifactId>net.java.html.boot</artifactId>
14.10 <version>${net.java.html.version}</version>
14.11 </dependency>
15.1 --- a/launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/Console.java Wed Dec 11 08:22:17 2013 +0100
15.2 +++ b/launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/Console.java Mon Jan 13 12:37:03 2014 +0100
15.3 @@ -25,8 +25,8 @@
15.4 import java.lang.reflect.Modifier;
15.5 import java.net.URL;
15.6 import java.util.Enumeration;
15.7 +import net.java.html.js.JavaScriptBody;
15.8 import netscape.javascript.JSObject;
15.9 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
15.10
15.11 /**
15.12 *
15.13 @@ -60,8 +60,7 @@
15.14 }
15.15
15.16 private static void beginTest(Case c) {
15.17 - Object[] arr = new Object[2];
15.18 - beginTest(c.getClassName() + "." + c.getMethodName(), c, arr);
15.19 + Object[] arr = beginTest(c.getClassName() + "." + c.getMethodName(), c, new Object[2]);
15.20 textArea = arr[0];
15.21 statusArea = arr[1];
15.22 }
15.23 @@ -102,23 +101,23 @@
15.24 + "ul.appendChild(li);\n"
15.25 + "arr[0] = pre;\n"
15.26 + "arr[1] = status;\n"
15.27 + + "return arr;"
15.28 )
15.29 - private static native void beginTest(String test, Case c, Object[] arr);
15.30 + private static native Object[] beginTest(String test, Case c, Object[] arr);
15.31
15.32 - @JavaScriptBody(args = { "url", "callback", "arr" }, body =
15.33 + @JavaScriptBody(args = { "url", "callback" }, javacall = true, body =
15.34 "var request = new XMLHttpRequest();\n"
15.35 + "request.open('GET', url, true);\n"
15.36 + "request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');\n"
15.37 + "request.onreadystatechange = function() {\n"
15.38 + " if (this.readyState!==4) return;\n"
15.39 + " try {\n"
15.40 - + " arr[0] = this.responseText;\n"
15.41 - + " callback.run();\n"
15.42 + + " callback.@org.apidesign.bck2brwsr.launcher.fximpl.OnMessage::onMessage(Ljava/lang/String;)(this.responseText);\n"
15.43 + " } catch (e) { alert(e); }\n"
15.44 + "};\n"
15.45 + "request.send();\n"
15.46 )
15.47 - private static native void loadText(String url, Runnable callback, String[] arr) throws IOException;
15.48 + private static native void loadText(String url, OnMessage callback) throws IOException;
15.49
15.50 public static void runHarness(String url) throws IOException {
15.51 new Console().harness(url);
15.52 @@ -129,7 +128,7 @@
15.53 Request r = new Request(url);
15.54 }
15.55
15.56 - private static class Request implements Runnable {
15.57 + private static class Request implements Runnable, OnMessage {
15.58 private final String[] arr = { null };
15.59 private final String url;
15.60 private Case c;
15.61 @@ -137,11 +136,17 @@
15.62
15.63 private Request(String url) throws IOException {
15.64 this.url = url;
15.65 - loadText(url, new Run(this), arr);
15.66 + loadText(url, this);
15.67 }
15.68 private Request(String url, String u) throws IOException {
15.69 this.url = url;
15.70 - loadText(u, new Run(this), arr);
15.71 + loadText(u, this);
15.72 + }
15.73 +
15.74 + @Override
15.75 + public void onMessage(String msg) {
15.76 + arr[0] = msg;
15.77 + run();
15.78 }
15.79
15.80 @Override
15.81 @@ -177,7 +182,7 @@
15.82 } catch (Exception ex) {
15.83 if (ex instanceof InterruptedException) {
15.84 log("Re-scheduling in 100ms");
15.85 - schedule(new Run(this), 100);
15.86 + schedule(this, 100);
15.87 return;
15.88 }
15.89 log(ex.getClass().getName() + ":" + ex.getMessage());
15.90 @@ -250,7 +255,11 @@
15.91 private static void turnAssetionStatusOn() {
15.92 }
15.93
15.94 - @JavaScriptBody(args = { "r", "time" }, body = "return window.setTimeout(function() { r.run(); }, time);")
15.95 + @JavaScriptBody(args = { "r", "time" }, javacall = true, body =
15.96 + "return window.setTimeout(function() { "
15.97 + + "r.@java.lang.Runnable::run()(); "
15.98 + + "}, time);"
15.99 + )
15.100 private static native Object schedule(Runnable r, int time);
15.101
15.102 private static final class Case {
16.1 --- a/launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/JVMBridge.java Wed Dec 11 08:22:17 2013 +0100
16.2 +++ b/launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/JVMBridge.java Mon Jan 13 12:37:03 2014 +0100
16.3 @@ -19,24 +19,30 @@
16.4
16.5 import java.io.BufferedReader;
16.6 import java.io.Reader;
16.7 -import org.apidesign.html.boot.spi.Fn;
16.8 import java.net.URL;
16.9 import java.util.ArrayList;
16.10 import java.util.Arrays;
16.11 import java.util.Collection;
16.12 import java.util.List;
16.13 import java.util.TooManyListenersException;
16.14 +import java.util.concurrent.Executor;
16.15 +import java.util.logging.Level;
16.16 +import java.util.logging.Logger;
16.17 +import javafx.application.Platform;
16.18 import javafx.beans.value.ChangeListener;
16.19 import javafx.scene.web.WebEngine;
16.20 import netscape.javascript.JSObject;
16.21 -import org.apidesign.html.boot.impl.FindResources;
16.22 -import org.apidesign.html.boot.impl.FnUtils;
16.23 +import org.apidesign.html.boot.spi.Fn;
16.24 +import org.netbeans.html.boot.impl.FindResources;
16.25 +import org.netbeans.html.boot.impl.FnUtils;
16.26
16.27 /**
16.28 *
16.29 * @author Jaroslav Tulach <jtulach@netbeans.org>
16.30 */
16.31 public final class JVMBridge {
16.32 + static final Logger LOG = Logger.getLogger(JVMBridge.class.getName());
16.33 +
16.34 private final WebEngine engine;
16.35 private final ClassLoader cl;
16.36 private final WebPresenter presenter;
16.37 @@ -70,11 +76,12 @@
16.38 }
16.39
16.40 public Class<?> loadClass(String name) throws ClassNotFoundException {
16.41 - FnUtils.currentPresenter(presenter);
16.42 + Fn.activate(presenter);
16.43 return Class.forName(name, true, cl);
16.44 }
16.45
16.46 - private final class WebPresenter implements FindResources, Fn.Presenter {
16.47 + private final class WebPresenter
16.48 + implements FindResources, Fn.Presenter, Fn.ToJavaScript, Fn.FromJavaScript, Executor {
16.49 @Override
16.50 public void findResources(String name, Collection<? super URL> results, boolean oneIsEnough) {
16.51 if (ldrs != null) for (ClassLoader l : ldrs) {
16.52 @@ -87,6 +94,9 @@
16.53
16.54 @Override
16.55 public Fn defineFn(String code, String... names) {
16.56 + return defineJSFn(code, names);
16.57 + }
16.58 + private JSFn defineJSFn(String code, String... names) {
16.59 StringBuilder sb = new StringBuilder();
16.60 sb.append("(function() {");
16.61 sb.append(" return function(");
16.62 @@ -122,6 +132,91 @@
16.63 }
16.64 engine.executeScript(sb.toString());
16.65 }
16.66 +
16.67 + @Override
16.68 + public Object toJava(Object js) {
16.69 + return checkArray(js);
16.70 + }
16.71 +
16.72 + @Override
16.73 + public Object toJavaScript(Object toReturn) {
16.74 + if (toReturn instanceof Object[]) {
16.75 + return convertArrays((Object[]) toReturn);
16.76 + }
16.77 + return toReturn;
16.78 + }
16.79 +
16.80 + @Override
16.81 + public void execute(Runnable command) {
16.82 + if (Platform.isFxApplicationThread()) {
16.83 + command.run();
16.84 + } else {
16.85 + Platform.runLater(command);
16.86 + }
16.87 + }
16.88 +
16.89 + final JSObject convertArrays(Object[] arr) {
16.90 + for (int i = 0; i < arr.length; i++) {
16.91 + if (arr[i] instanceof Object[]) {
16.92 + arr[i] = convertArrays((Object[]) arr[i]);
16.93 + }
16.94 + }
16.95 + final JSObject wrapArr = (JSObject) wrapArrFn().call("array", arr); // NOI18N
16.96 + return wrapArr;
16.97 + }
16.98 +
16.99 + private JSObject wrapArrImpl;
16.100 +
16.101 + private final JSObject wrapArrFn() {
16.102 + if (wrapArrImpl == null) {
16.103 + try {
16.104 + wrapArrImpl = (JSObject) defineJSFn(" var k = {};"
16.105 + + " k.array= function() {"
16.106 + + " return Array.prototype.slice.call(arguments);"
16.107 + + " };"
16.108 + + " return k;"
16.109 + ).invokeImpl(null, false);
16.110 + } catch (Exception ex) {
16.111 + throw new IllegalStateException(ex);
16.112 + }
16.113 + }
16.114 + return wrapArrImpl;
16.115 + }
16.116 +
16.117 + final Object checkArray(Object val) {
16.118 + int length = ((Number) arraySizeFn().call("array", val, null)).intValue();
16.119 + if (length == -1) {
16.120 + return val;
16.121 + }
16.122 + Object[] arr = new Object[length];
16.123 + arraySizeFn().call("array", val, arr);
16.124 + return arr;
16.125 + }
16.126 + private JSObject arraySize;
16.127 +
16.128 + private final JSObject arraySizeFn() {
16.129 + if (arraySize == null) {
16.130 + try {
16.131 + arraySize = (JSObject) defineJSFn(" var k = {};"
16.132 + + " k.array = function(arr, to) {"
16.133 + + " if (to === null) {"
16.134 + + " if (Object.prototype.toString.call(arr) === '[object Array]') return arr.length;"
16.135 + + " else return -1;"
16.136 + + " } else {"
16.137 + + " var l = arr.length;"
16.138 + + " for (var i = 0; i < l; i++) to[i] = arr[i];"
16.139 + + " return l;"
16.140 + + " }"
16.141 + + " };"
16.142 + + " return k;"
16.143 + ).invokeImpl(null, false);
16.144 + } catch (Exception ex) {
16.145 + throw new IllegalStateException(ex);
16.146 + }
16.147 + }
16.148 + return arraySize;
16.149 + }
16.150 +
16.151 }
16.152
16.153 private static final class JSFn extends Fn {
16.154 @@ -134,12 +229,29 @@
16.155
16.156 @Override
16.157 public Object invoke(Object thiz, Object... args) throws Exception {
16.158 + return invokeImpl(thiz, true, args);
16.159 + }
16.160 +
16.161 + final Object invokeImpl(Object thiz, boolean arrayChecks, Object... args) throws Exception {
16.162 try {
16.163 List<Object> all = new ArrayList<Object>(args.length + 1);
16.164 all.add(thiz == null ? fn : thiz);
16.165 - all.addAll(Arrays.asList(args));
16.166 + for (int i = 0; i < args.length; i++) {
16.167 + if (arrayChecks && args[i] instanceof Object[]) {
16.168 + Object[] arr = (Object[]) args[i];
16.169 + Object conv = ((WebPresenter) presenter()).convertArrays(arr);
16.170 + args[i] = conv;
16.171 + }
16.172 + all.add(args[i]);
16.173 + }
16.174 Object ret = fn.call("call", all.toArray()); // NOI18N
16.175 - return ret == fn ? null : ret;
16.176 + if (ret == fn) {
16.177 + return null;
16.178 + }
16.179 + if (!arrayChecks) {
16.180 + return ret;
16.181 + }
16.182 + return ((WebPresenter) presenter()).checkArray(ret);
16.183 } catch (Error t) {
16.184 t.printStackTrace();
16.185 throw t;
17.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
17.2 +++ b/launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/OnMessage.java Mon Jan 13 12:37:03 2014 +0100
17.3 @@ -0,0 +1,26 @@
17.4 +/**
17.5 + * Back 2 Browser Bytecode Translator
17.6 + * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
17.7 + *
17.8 + * This program is free software: you can redistribute it and/or modify
17.9 + * it under the terms of the GNU General Public License as published by
17.10 + * the Free Software Foundation, version 2 of the License.
17.11 + *
17.12 + * This program is distributed in the hope that it will be useful,
17.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
17.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17.15 + * GNU General Public License for more details.
17.16 + *
17.17 + * You should have received a copy of the GNU General Public License
17.18 + * along with this program. Look for COPYING file in the top folder.
17.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
17.20 + */
17.21 +package org.apidesign.bck2brwsr.launcher.fximpl;
17.22 +
17.23 +/**
17.24 + *
17.25 + * @author Jaroslav Tulach <jtulach@netbeans.org>
17.26 + */
17.27 +interface OnMessage {
17.28 + public void onMessage(String msg);
17.29 +}
18.1 --- a/launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/Run.java Wed Dec 11 08:22:17 2013 +0100
18.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
18.3 @@ -1,35 +0,0 @@
18.4 -/**
18.5 - * Back 2 Browser Bytecode Translator
18.6 - * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
18.7 - *
18.8 - * This program is free software: you can redistribute it and/or modify
18.9 - * it under the terms of the GNU General Public License as published by
18.10 - * the Free Software Foundation, version 2 of the License.
18.11 - *
18.12 - * This program is distributed in the hope that it will be useful,
18.13 - * but WITHOUT ANY WARRANTY; without even the implied warranty of
18.14 - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18.15 - * GNU General Public License for more details.
18.16 - *
18.17 - * You should have received a copy of the GNU General Public License
18.18 - * along with this program. Look for COPYING file in the top folder.
18.19 - * If not, see http://opensource.org/licenses/GPL-2.0.
18.20 - */
18.21 -
18.22 -package org.apidesign.bck2brwsr.launcher.fximpl;
18.23 -
18.24 -/**
18.25 - *
18.26 - * @author Jaroslav Tulach <jtulach@netbeans.org>
18.27 - */
18.28 -public final class Run implements Runnable {
18.29 - private final Runnable r;
18.30 - Run(Runnable r) {
18.31 - this.r = r;
18.32 - }
18.33 -
18.34 - @Override
18.35 - public void run() {
18.36 - r.run();
18.37 - }
18.38 -}
19.1 --- a/launcher/fx/src/test/java/org/apidesign/bck2brwsr/launcher/fximpl/JsClassLoaderTest.java Wed Dec 11 08:22:17 2013 +0100
19.2 +++ b/launcher/fx/src/test/java/org/apidesign/bck2brwsr/launcher/fximpl/JsClassLoaderTest.java Mon Jan 13 12:37:03 2014 +0100
19.3 @@ -31,8 +31,8 @@
19.4 import javax.script.ScriptEngineManager;
19.5 import javax.script.ScriptException;
19.6 import org.apidesign.html.boot.spi.Fn;
19.7 -import org.apidesign.html.boot.impl.FindResources;
19.8 -import org.apidesign.html.boot.impl.FnUtils;
19.9 +import org.netbeans.html.boot.impl.FindResources;
19.10 +import org.netbeans.html.boot.impl.FnUtils;
19.11 import static org.testng.Assert.*;
19.12 import org.testng.annotations.BeforeClass;
19.13 import org.testng.annotations.BeforeMethod;
19.14 @@ -118,7 +118,7 @@
19.15 }
19.16
19.17 @BeforeMethod public void registerPresenter() {
19.18 - FnUtils.currentPresenter(presenter);
19.19 + Fn.activate(presenter);
19.20 }
19.21
19.22 @Test public void noParamMethod() throws Throwable {
20.1 --- a/launcher/fx/src/test/java/org/apidesign/bck2brwsr/launcher/fximpl/JsMethods.java Wed Dec 11 08:22:17 2013 +0100
20.2 +++ b/launcher/fx/src/test/java/org/apidesign/bck2brwsr/launcher/fximpl/JsMethods.java Mon Jan 13 12:37:03 2014 +0100
20.3 @@ -17,7 +17,7 @@
20.4 */
20.5 package org.apidesign.bck2brwsr.launcher.fximpl;
20.6
20.7 -import org.apidesign.bck2brwsr.core.JavaScriptBody;
20.8 +import net.java.html.js.JavaScriptBody;
20.9
20.10 /**
20.11 *
21.1 --- a/pom.xml Wed Dec 11 08:22:17 2013 +0100
21.2 +++ b/pom.xml Mon Jan 13 12:37:03 2014 +0100
21.3 @@ -15,7 +15,7 @@
21.4 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21.5 <netbeans.version>RELEASE74</netbeans.version>
21.6 <license>COPYING</license>
21.7 - <net.java.html.version>0.6</net.java.html.version>
21.8 + <net.java.html.version>0.7</net.java.html.version>
21.9 <netbeans.compile.on.save>none</netbeans.compile.on.save>
21.10 </properties>
21.11 <modules>
22.1 --- a/rt/emul/mini/src/main/java/java/lang/Class.java Wed Dec 11 08:22:17 2013 +0100
22.2 +++ b/rt/emul/mini/src/main/java/java/lang/Class.java Mon Jan 13 12:37:03 2014 +0100
22.3 @@ -632,6 +632,20 @@
22.4 return getAccess();
22.5 }
22.6
22.7 + /**
22.8 + * If the class or interface represented by this {@code Class} object
22.9 + * is a member of another class, returns the {@code Class} object
22.10 + * representing the class in which it was declared. This method returns
22.11 + * null if this class or interface is not a member of any other class. If
22.12 + * this {@code Class} object represents an array class, a primitive
22.13 + * type, or void,then this method returns null.
22.14 + *
22.15 + * @return the declaring class for this class
22.16 + * @since JDK1.1
22.17 + */
22.18 + public Class<?> getDeclaringClass() {
22.19 + throw new SecurityException();
22.20 + }
22.21
22.22 /**
22.23 * Returns the simple name of the underlying class as given in the
23.1 --- a/rt/emul/mini/src/main/java/java/lang/Throwable.java Wed Dec 11 08:22:17 2013 +0100
23.2 +++ b/rt/emul/mini/src/main/java/java/lang/Throwable.java Mon Jan 13 12:37:03 2014 +0100
23.3 @@ -638,8 +638,11 @@
23.4 * ... 2 more
23.5 * </pre>
23.6 */
23.7 - @JavaScriptBody(args = { }, body = "console.warn(this.toString());")
23.8 - public native void printStackTrace();
23.9 + public void printStackTrace() {
23.10 + warn(getClass().getName() + ": " + getMessage());
23.11 + }
23.12 + @JavaScriptBody(args = { "msg" }, body = "if (console) console.warn(msg.toString());")
23.13 + private native void warn(String msg);
23.14
23.15 /**
23.16 * Prints this throwable and its backtrace to the specified print stream.
24.1 --- a/rt/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/lang/System.java Wed Dec 11 08:22:17 2013 +0100
24.2 +++ b/rt/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/lang/System.java Mon Jan 13 12:37:03 2014 +0100
24.3 @@ -19,6 +19,7 @@
24.4
24.5 import java.lang.reflect.Method;
24.6 import org.apidesign.bck2brwsr.core.JavaScriptBody;
24.7 +import org.apidesign.bck2brwsr.core.JavaScriptOnly;
24.8
24.9 /**
24.10 *
24.11 @@ -71,4 +72,27 @@
24.12 }
24.13 @JavaScriptBody(args = { "obj" }, body="return vm.java_lang_Object(false).hashCode__I.call(obj);")
24.14 public static native int identityHashCode(Object obj);
24.15 +
24.16 + @JavaScriptOnly(name = "toJS", value = "function(v) {\n" +
24.17 + " if (v === null) return null;\n" +
24.18 + " if (Object.prototype.toString.call(v) === '[object Array]') {\n" +
24.19 + " return vm.org_apidesign_bck2brwsr_emul_lang_System(false).convArray__Ljava_lang_Object_2Ljava_lang_Object_2(v);\n" +
24.20 + " }\n" +
24.21 + " return v.valueOf();\n" +
24.22 + "}\n"
24.23 + )
24.24 + public static native int toJS();
24.25 +
24.26 + private static Object convArray(Object o) {
24.27 + if (o instanceof Object[]) {
24.28 + Object[] arr = (Object[]) o;
24.29 + final int l = arr.length;
24.30 + Object[] ret = new Object[l];
24.31 + for (int i = 0; i < l; i++) {
24.32 + ret[i] = convArray(arr[i]);
24.33 + }
24.34 + return ret;
24.35 + }
24.36 + return o;
24.37 + }
24.38 }
25.1 --- a/rt/vm/pom.xml Wed Dec 11 08:22:17 2013 +0100
25.2 +++ b/rt/vm/pom.xml Mon Jan 13 12:37:03 2014 +0100
25.3 @@ -154,7 +154,7 @@
25.4 <scope>compile</scope>
25.5 </dependency>
25.6 <dependency>
25.7 - <groupId>org.apidesign.html</groupId>
25.8 + <groupId>org.netbeans.html</groupId>
25.9 <artifactId>net.java.html.boot</artifactId>
25.10 <scope>test</scope>
25.11 <version>${net.java.html.version}</version>
26.1 --- a/rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java Wed Dec 11 08:22:17 2013 +0100
26.2 +++ b/rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java Mon Jan 13 12:37:03 2014 +0100
26.3 @@ -1623,6 +1623,7 @@
26.4 String[] args = new String[30];
26.5 String body;
26.6 boolean javacall;
26.7 + boolean html4j;
26.8
26.9 @Override
26.10 protected void visitAttr(String type, String attr, String at, String value) {
26.11 @@ -1636,6 +1637,7 @@
26.12 }
26.13 }
26.14 if (type.equals(htmlType)) {
26.15 + html4j = true;
26.16 if ("body".equals(attr)) {
26.17 body = value;
26.18 } else if ("args".equals(attr)) {
26.19 @@ -1659,12 +1661,18 @@
26.20 out.append(" = function(");
26.21 String space = "";
26.22 int index = 0;
26.23 + StringBuilder toValue = new StringBuilder();
26.24 for (int i = 0; i < cnt.length(); i++) {
26.25 out.append(space);
26.26 space = outputArg(out, p.args, index);
26.27 + if (p.html4j && space.length() > 0) {
26.28 + toValue.append("\n ").append(p.args[index]).append(" = vm.org_apidesign_bck2brwsr_emul_lang_System(false).toJS(").
26.29 + append(p.args[index]).append(");");
26.30 + }
26.31 index++;
26.32 }
26.33 out.append(") {").append("\n");
26.34 + out.append(toValue.toString());
26.35 if (p.javacall) {
26.36 int lastSlash = jc.getClassName().lastIndexOf('/');
26.37 final String pkg = jc.getClassName().substring(0, lastSlash);
26.38 @@ -1765,6 +1773,23 @@
26.39 final String fqnu = fqn.replace('.', '_');
26.40 final String rfqn = mangleClassName(fqnu);
26.41 final String rm = mangleMethodName(method);
26.42 + final String srp;
26.43 + {
26.44 + StringBuilder pb = new StringBuilder();
26.45 + int len = params.length();
26.46 + int indx = 0;
26.47 + while (indx < len) {
26.48 + char ch = params.charAt(indx);
26.49 + if (ch == '[' || ch == 'L') {
26.50 + pb.append("Ljava/lang/Object;");
26.51 + indx = params.indexOf(';', indx) + 1;
26.52 + } else {
26.53 + pb.append(ch);
26.54 + indx++;
26.55 + }
26.56 + }
26.57 + srp = mangleSig(pb.toString());
26.58 + }
26.59 final String rp = mangleSig(params);
26.60 final String mrp = mangleMethodName(rp);
26.61 sb.append(rfqn).append("$").append(rm).
26.62 @@ -1772,7 +1797,7 @@
26.63 if (!isStatic) {
26.64 sb.append('L').append(fqnu).append("_2");
26.65 }
26.66 - sb.append(rp);
26.67 + sb.append(srp);
26.68 return sb.toString();
26.69 }
26.70