1.1 --- a/ko/bck2brwsr/pom.xml Wed Jun 26 19:37:34 2013 +0200
1.2 +++ b/ko/bck2brwsr/pom.xml Wed Jun 26 19:57:38 2013 +0200
1.3 @@ -78,12 +78,12 @@
1.4 <dependency>
1.5 <groupId>org.apidesign.html</groupId>
1.6 <artifactId>net.java.html.json</artifactId>
1.7 - <version>0.4-SNAPSHOT</version>
1.8 + <version>${net.java.html.version}</version>
1.9 </dependency>
1.10 <dependency>
1.11 <groupId>org.apidesign.html</groupId>
1.12 <artifactId>net.java.html.json.tck</artifactId>
1.13 - <version>0.4-SNAPSHOT</version>
1.14 + <version>${net.java.html.version}</version>
1.15 <scope>test</scope>
1.16 </dependency>
1.17 <dependency>
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/ko/fx/pom.xml Wed Jun 26 19:57:38 2013 +0200
2.3 @@ -0,0 +1,84 @@
2.4 +<?xml version="1.0"?>
2.5 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2.6 + <modelVersion>4.0.0</modelVersion>
2.7 + <parent>
2.8 + <groupId>org.apidesign.bck2brwsr</groupId>
2.9 + <artifactId>ko</artifactId>
2.10 + <version>0.8-SNAPSHOT</version>
2.11 + </parent>
2.12 + <groupId>org.apidesign.html</groupId>
2.13 + <artifactId>ko-fx</artifactId>
2.14 + <version>0.8-SNAPSHOT</version>
2.15 + <name>Knockout.fx in Brwsr</name>
2.16 + <url>http://maven.apache.org</url>
2.17 + <properties>
2.18 + <jfxrt.jar>${java.home}/lib/jfxrt.jar</jfxrt.jar>
2.19 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
2.20 + </properties>
2.21 + <build>
2.22 + <plugins>
2.23 + <plugin>
2.24 + <groupId>org.apache.maven.plugins</groupId>
2.25 + <artifactId>maven-javadoc-plugin</artifactId>
2.26 + <configuration>
2.27 + <skip>false</skip>
2.28 + </configuration>
2.29 + </plugin>
2.30 + </plugins>
2.31 + </build>
2.32 + <dependencies>
2.33 + <dependency>
2.34 + <groupId>com.oracle</groupId>
2.35 + <artifactId>javafx</artifactId>
2.36 + <version>2.2</version>
2.37 + <scope>system</scope>
2.38 + <systemPath>${jfxrt.jar}</systemPath>
2.39 + </dependency>
2.40 + <dependency>
2.41 + <groupId>org.json</groupId>
2.42 + <artifactId>json</artifactId>
2.43 + <version>20090211</version>
2.44 + <type>jar</type>
2.45 + </dependency>
2.46 + <dependency>
2.47 + <groupId>org.apidesign.html</groupId>
2.48 + <artifactId>net.java.html.json</artifactId>
2.49 + <version>${net.java.html.version}</version>
2.50 + </dependency>
2.51 + <dependency>
2.52 + <groupId>org.testng</groupId>
2.53 + <artifactId>testng</artifactId>
2.54 + <scope>test</scope>
2.55 + </dependency>
2.56 + <dependency>
2.57 + <groupId>${project.groupId}</groupId>
2.58 + <artifactId>net.java.html.json.tck</artifactId>
2.59 + <version>${net.java.html.version}</version>
2.60 + <scope>test</scope>
2.61 + </dependency>
2.62 + <dependency>
2.63 + <groupId>org.netbeans.api</groupId>
2.64 + <artifactId>org-openide-util</artifactId>
2.65 + <scope>provided</scope>
2.66 + </dependency>
2.67 + <dependency>
2.68 + <groupId>org.apidesign.bck2brwsr</groupId>
2.69 + <artifactId>launcher.fx</artifactId>
2.70 + <version>${project.version}</version>
2.71 + <scope>test</scope>
2.72 + </dependency>
2.73 + <dependency>
2.74 + <groupId>org.apidesign.html</groupId>
2.75 + <artifactId>net.java.html.boot</artifactId>
2.76 + <version>${project.version}</version>
2.77 + <type>jar</type>
2.78 + </dependency>
2.79 + <dependency>
2.80 + <groupId>org.apidesign.bck2brwsr</groupId>
2.81 + <artifactId>vmtest</artifactId>
2.82 + <version>${project.version}</version>
2.83 + <scope>test</scope>
2.84 + <type>jar</type>
2.85 + </dependency>
2.86 + </dependencies>
2.87 +</project>
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/ko/fx/src/main/java/org/apidesign/bck2brwsr/kofx/Console.java Wed Jun 26 19:57:38 2013 +0200
3.3 @@ -0,0 +1,52 @@
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.kofx;
3.22 +
3.23 +import java.util.logging.Logger;
3.24 +import net.java.html.js.JavaScriptBody;
3.25 +
3.26 +/** This is an implementation package - just
3.27 + * include its JAR on classpath and use official {@link Context} API
3.28 + * to access the functionality.
3.29 + * <p>
3.30 + * Redirects JavaScript's messages to Java's {@link Logger}.
3.31 + *
3.32 + * @author Jaroslav Tulach <jtulach@netbeans.org>
3.33 + */
3.34 +public final class Console {
3.35 + private static final Logger LOG = Logger.getLogger(Console.class.getName());
3.36 +
3.37 + private Console() {
3.38 + }
3.39 +
3.40 + static void register() {
3.41 + registerImpl(new Console());
3.42 + }
3.43 +
3.44 + @JavaScriptBody(args = { "jconsole" }, body =
3.45 + "console.log = function(m) { jconsole.log(m); };" +
3.46 + "console.info = function(m) { jconsole.log(m); };" +
3.47 + "console.error = function(m) { jconsole.log(m); };" +
3.48 + "console.warn = function(m) { jconsole.log(m); };"
3.49 + )
3.50 + private static native void registerImpl(Console c);
3.51 +
3.52 + public void log(String msg) {
3.53 + LOG.info(msg);
3.54 + }
3.55 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/ko/fx/src/main/java/org/apidesign/bck2brwsr/kofx/FXContext.java Wed Jun 26 19:57:38 2013 +0200
4.3 @@ -0,0 +1,106 @@
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.kofx;
4.22 +
4.23 +import java.io.IOException;
4.24 +import java.io.InputStream;
4.25 +import java.util.ServiceLoader;
4.26 +import java.util.logging.Logger;
4.27 +import netscape.javascript.JSObject;
4.28 +import org.apidesign.html.context.spi.Contexts;
4.29 +import org.apidesign.html.json.spi.FunctionBinding;
4.30 +import org.apidesign.html.json.spi.JSONCall;
4.31 +import org.apidesign.html.json.spi.PropertyBinding;
4.32 +import org.apidesign.html.json.spi.Technology;
4.33 +import org.apidesign.html.json.spi.Transfer;
4.34 +import org.openide.util.lookup.ServiceProvider;
4.35 +
4.36 +/** This is an implementation package - just
4.37 + * include its JAR on classpath and use official {@link Context} API
4.38 + * to access the functionality.
4.39 + * <p>
4.40 + * Registers {@link ContextProvider}, so {@link ServiceLoader} can find it.
4.41 + *
4.42 + * @author Jaroslav Tulach <jtulach@netbeans.org>
4.43 + */
4.44 +@ServiceProvider(service = Contexts.Provider.class)
4.45 +public final class FXContext
4.46 +implements Technology<JSObject>, Transfer, Contexts.Provider {
4.47 + static final Logger LOG = Logger.getLogger(FXContext.class.getName());
4.48 +
4.49 + @Override
4.50 + public void fillContext(Contexts.Builder context, Class<?> requestor) {
4.51 + context.register(Technology.class, this, 100);
4.52 + context.register(Transfer.class, this, 100);
4.53 + }
4.54 +
4.55 + @Override
4.56 + public JSObject wrapModel(Object model) {
4.57 + return (JSObject) Knockout.createBinding(model).koData();
4.58 + }
4.59 +
4.60 + @Override
4.61 + public void bind(PropertyBinding b, Object model, JSObject data) {
4.62 + final boolean isList = false;
4.63 + final boolean isPrimitive = false;
4.64 + Knockout.bind(data, model, b, isPrimitive, isList);
4.65 + }
4.66 +
4.67 + @Override
4.68 + public void valueHasMutated(JSObject data, String propertyName) {
4.69 + Knockout.valueHasMutated(data, propertyName);
4.70 + }
4.71 +
4.72 + @Override
4.73 + public void expose(FunctionBinding fb, Object model, JSObject d) {
4.74 + Knockout.expose(d, fb);
4.75 + }
4.76 +
4.77 + @Override
4.78 + public void applyBindings(JSObject data) {
4.79 + Knockout.applyBindings(data);
4.80 + }
4.81 +
4.82 + @Override
4.83 + public Object wrapArray(Object[] arr) {
4.84 + return Knockout.toArray(arr);
4.85 + }
4.86 +
4.87 + @Override
4.88 + public void extract(Object obj, String[] props, Object[] values) {
4.89 + LoadJSON.extractJSON(obj, props, values);
4.90 + }
4.91 +
4.92 + @Override
4.93 + public void loadJSON(final JSONCall call) {
4.94 + LoadJSON.loadJSON(call);
4.95 + }
4.96 +
4.97 + @Override
4.98 + public <M> M toModel(Class<M> modelClass, Object data) {
4.99 + if (data instanceof JSObject) {
4.100 + data = ((JSObject)data).getMember("ko-fx.model"); // NOI18N
4.101 + }
4.102 + return modelClass.cast(data);
4.103 + }
4.104 +
4.105 + @Override
4.106 + public Object toJSON(InputStream is) throws IOException {
4.107 + return LoadJSON.parse(is);
4.108 + }
4.109 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/ko/fx/src/main/java/org/apidesign/bck2brwsr/kofx/Knockout.java Wed Jun 26 19:57:38 2013 +0200
5.3 @@ -0,0 +1,196 @@
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.kofx;
5.22 +
5.23 +import java.io.BufferedReader;
5.24 +import java.io.IOException;
5.25 +import java.io.InputStream;
5.26 +import java.io.InputStreamReader;
5.27 +import java.util.logging.Level;
5.28 +import java.util.logging.Logger;
5.29 +import net.java.html.js.JavaScriptBody;
5.30 +import net.java.html.json.Model;
5.31 +import netscape.javascript.JSObject;
5.32 +import org.apidesign.html.json.spi.FunctionBinding;
5.33 +import org.apidesign.html.json.spi.PropertyBinding;
5.34 +
5.35 +/** This is an implementation package - just
5.36 + * include its JAR on classpath and use official {@link Context} API
5.37 + * to access the functionality.
5.38 + * <p>
5.39 + * Provides binding between {@link Model models} and knockout.js running
5.40 + * inside a JavaFX WebView.
5.41 + *
5.42 + * @author Jaroslav Tulach <jtulach@netbeans.org>
5.43 + */
5.44 +public final class Knockout {
5.45 + private static final Logger LOG = Logger.getLogger(Knockout.class.getName());
5.46 + /** used by tests */
5.47 + static Knockout next;
5.48 + private final Object model;
5.49 +
5.50 + Knockout(Object model) {
5.51 + this.model = model == null ? this : model;
5.52 + }
5.53 +
5.54 + public Object koData() {
5.55 + return model;
5.56 + }
5.57 +
5.58 + static Object toArray(Object[] arr) {
5.59 + return InvokeJS.KObject.call("array", arr);
5.60 + }
5.61 +
5.62 + private static int cnt;
5.63 + public static <M> Knockout createBinding(Object model) {
5.64 + Object bindings = InvokeJS.create(model, ++cnt);
5.65 + return new Knockout(bindings);
5.66 + }
5.67 +
5.68 + public void valueHasMutated(String prop) {
5.69 + valueHasMutated((JSObject) model, prop);
5.70 + }
5.71 + public static void valueHasMutated(JSObject model, String prop) {
5.72 + LOG.log(Level.FINE, "property mutated: {0}", prop);
5.73 + try {
5.74 + Object koProp = model.getMember(prop);
5.75 + if (koProp instanceof JSObject) {
5.76 + ((JSObject)koProp).call("valueHasMutated");
5.77 + }
5.78 + } catch (Throwable t) {
5.79 + LOG.log(Level.WARNING, "valueHasMutated failed for " + model + " prop: " + prop, t);
5.80 + }
5.81 + }
5.82 +
5.83 + static void bind(
5.84 + Object bindings, Object model, PropertyBinding pb, boolean primitive, boolean array
5.85 + ) {
5.86 + final String prop = pb.getPropertyName();
5.87 + try {
5.88 + InvokeJS.bind(bindings, pb, prop, "getValue", pb.isReadOnly() ? null : "setValue", primitive, array);
5.89 +
5.90 + ((JSObject)bindings).setMember("ko-fx.model", model);
5.91 + LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
5.92 + } catch (Throwable ex) {
5.93 + LOG.log(Level.WARNING, "binding failed for {0} on {1}", new Object[]{prop, bindings});
5.94 + }
5.95 + }
5.96 + static void expose(Object bindings, FunctionBinding f) {
5.97 + final String prop = f.getFunctionName();
5.98 + try {
5.99 + InvokeJS.expose(bindings, f, prop, "call");
5.100 + } catch (Throwable ex) {
5.101 + LOG.log(Level.SEVERE, "Cannot define binding for " + prop + " in model " + f, ex);
5.102 + }
5.103 + }
5.104 +
5.105 + static void applyBindings(Object bindings) {
5.106 + InvokeJS.applyBindings(bindings);
5.107 + }
5.108 +
5.109 + private static final class InvokeJS {
5.110 + static final JSObject KObject;
5.111 +
5.112 + static {
5.113 + final InputStream koScript = Knockout.class.getResourceAsStream("knockout-2.2.1.js");
5.114 + assert koScript != null : "Can't load knockout.js";
5.115 + BufferedReader r = new BufferedReader(new InputStreamReader(koScript));
5.116 + StringBuilder sb = new StringBuilder();
5.117 + for (;;) {
5.118 + try {
5.119 + String l = r.readLine();
5.120 + if (l == null) {
5.121 + break;
5.122 + }
5.123 + sb.append(l).append('\n');
5.124 + } catch (IOException ex) {
5.125 + throw new IllegalStateException(ex);
5.126 + }
5.127 + }
5.128 + exec(sb.toString());
5.129 + Object ko = exec("ko");
5.130 + assert ko != null : "Knockout library successfully defined 'ko'";
5.131 +
5.132 + Console.register();
5.133 + KObject = (JSObject) kObj();
5.134 + }
5.135 +
5.136 + @JavaScriptBody(args = { "s" }, body = "return eval(s);")
5.137 + private static native Object exec(String s);
5.138 +
5.139 + @JavaScriptBody(args = {}, body =
5.140 + " var k = {};"
5.141 + + " k.array= function() {"
5.142 + + " return Array.prototype.slice.call(arguments);"
5.143 + + " };"
5.144 + + " return k;"
5.145 + )
5.146 + private static native Object kObj();
5.147 +
5.148 + @JavaScriptBody(args = { "value", "cnt " }, body =
5.149 + " var ret = {};"
5.150 + + " ret.toString = function() { return 'KObject' + cnt + ' value: ' + value + ' props: ' + Object.keys(this); };"
5.151 + + " return ret;"
5.152 + )
5.153 + static native Object create(Object value, int cnt);
5.154 +
5.155 + @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
5.156 + " bindings[prop] = function(data, ev) {"
5.157 + // + " console.log(\" callback on prop: \" + prop);"
5.158 + + " model[sig](data, ev);"
5.159 + + " };"
5.160 + )
5.161 + static native Object expose(Object bindings, Object model, String prop, String sig);
5.162 +
5.163 +
5.164 + @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
5.165 + " var bnd = {"
5.166 + + " read: function() {"
5.167 + + " try {"
5.168 + + " var v = model[getter]();"
5.169 + // + " console.log(\" getter value \" + v + \" for property \" + prop);"
5.170 + // + " try { v = v.koData(); } catch (ignore) {"
5.171 + // + " console.log(\"Cannot convert to koData: \" + ignore);"
5.172 + // + " };"
5.173 + // + " console.log(\" getter ret value \" + v);"
5.174 + // + " for (var pn in v) {"
5.175 + // + " console.log(\" prop: \" + pn + \" + in + \" + v + \" = \" + v[pn]);"
5.176 + // + " if (typeof v[pn] == \"function\") console.log(\" its function value:\" + v[pn]());"
5.177 + // + " }"
5.178 + // + " console.log(\" all props printed for \" + (typeof v));"
5.179 + + " return v;"
5.180 + + " } catch (e) {"
5.181 + + " alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
5.182 + + " }"
5.183 + + " },"
5.184 + + " owner: bindings"
5.185 + // + " ,deferEvaluation: true"
5.186 + + " };"
5.187 + + " if (setter != null) {"
5.188 + + " bnd.write = function(val) {"
5.189 + + " model[setter](primitive ? new Number(val) : val);"
5.190 + + " };"
5.191 + + " };"
5.192 + + " bindings[prop] = ko.computed(bnd);"
5.193 + )
5.194 + static native void bind(Object binding, Object model, String prop, String getter, String setter, boolean primitive, boolean array);
5.195 +
5.196 + @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
5.197 + private static native void applyBindings(Object bindings);
5.198 + }
5.199 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/ko/fx/src/main/java/org/apidesign/bck2brwsr/kofx/LoadJSON.java Wed Jun 26 19:57:38 2013 +0200
6.3 @@ -0,0 +1,234 @@
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.kofx;
6.22 +
6.23 +import java.io.IOException;
6.24 +import java.io.InputStream;
6.25 +import java.io.InputStreamReader;
6.26 +import java.io.OutputStream;
6.27 +import java.io.PushbackInputStream;
6.28 +import java.io.Reader;
6.29 +import java.net.HttpURLConnection;
6.30 +import java.net.MalformedURLException;
6.31 +import java.net.URL;
6.32 +import java.net.URLConnection;
6.33 +import java.util.Iterator;
6.34 +import java.util.concurrent.Executor;
6.35 +import java.util.concurrent.Executors;
6.36 +import java.util.logging.Level;
6.37 +import java.util.logging.Logger;
6.38 +import javafx.application.Platform;
6.39 +import net.java.html.js.JavaScriptBody;
6.40 +import netscape.javascript.JSObject;
6.41 +import org.apidesign.html.json.spi.JSONCall;
6.42 +import org.json.JSONArray;
6.43 +import org.json.JSONException;
6.44 +import org.json.JSONObject;
6.45 +import org.json.JSONTokener;
6.46 +
6.47 +/** This is an implementation package - just
6.48 + * include its JAR on classpath and use official {@link Context} API
6.49 + * to access the functionality.
6.50 + *
6.51 + * @author Jaroslav Tulach <jtulach@netbeans.org>
6.52 + */
6.53 +final class LoadJSON implements Runnable {
6.54 + private static final Logger LOG = FXContext.LOG;
6.55 + private static final Executor REQ = Executors.newCachedThreadPool();
6.56 +
6.57 + private final JSONCall call;
6.58 + private final URL base;
6.59 + private Throwable error;
6.60 + private Object json;
6.61 +
6.62 +
6.63 + private LoadJSON(JSONCall call) {
6.64 + this.call = call;
6.65 + URL b;
6.66 + try {
6.67 + b = new URL(findBaseURL());
6.68 + } catch (MalformedURLException ex) {
6.69 + LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
6.70 + b = null;
6.71 + }
6.72 + this.base = b;
6.73 + }
6.74 +
6.75 + public static void loadJSON(JSONCall call) {
6.76 + REQ.execute(new LoadJSON((call)));
6.77 + }
6.78 +
6.79 + @Override
6.80 + public void run() {
6.81 + if (Platform.isFxApplicationThread()) {
6.82 + if (error != null) {
6.83 + call.notifyError(error);
6.84 + } else {
6.85 + call.notifySuccess(json);
6.86 + }
6.87 + return;
6.88 + }
6.89 + final String url;
6.90 + if (call.isJSONP()) {
6.91 + url = call.composeURL("dummy");
6.92 + } else {
6.93 + url = call.composeURL(null);
6.94 + }
6.95 + try {
6.96 + final URL u = new URL(base, url.replace(" ", "%20"));
6.97 + URLConnection conn = u.openConnection();
6.98 + if (conn instanceof HttpURLConnection) {
6.99 + HttpURLConnection huc = (HttpURLConnection) conn;
6.100 + if (call.getMethod() != null) {
6.101 + huc.setRequestMethod(call.getMethod());
6.102 + }
6.103 + if (call.isDoOutput()) {
6.104 + huc.setDoOutput(true);
6.105 + final OutputStream os = huc.getOutputStream();
6.106 + call.writeData(os);
6.107 + os.flush();
6.108 + }
6.109 + }
6.110 + final PushbackInputStream is = new PushbackInputStream(
6.111 + conn.getInputStream(), 1
6.112 + );
6.113 + boolean array = false;
6.114 + boolean string = false;
6.115 + if (call.isJSONP()) {
6.116 + for (;;) {
6.117 + int ch = is.read();
6.118 + if (ch == -1) {
6.119 + break;
6.120 + }
6.121 + if (ch == '[') {
6.122 + is.unread(ch);
6.123 + array = true;
6.124 + break;
6.125 + }
6.126 + if (ch == '{') {
6.127 + is.unread(ch);
6.128 + break;
6.129 + }
6.130 + }
6.131 + } else {
6.132 + int ch = is.read();
6.133 + if (ch == -1) {
6.134 + string = true;
6.135 + } else {
6.136 + array = ch == '[';
6.137 + is.unread(ch);
6.138 + if (!array && ch != '{') {
6.139 + string = true;
6.140 + }
6.141 + }
6.142 + }
6.143 + try {
6.144 + if (string) {
6.145 + throw new JSONException("");
6.146 + }
6.147 + Reader r = new InputStreamReader(is, "UTF-8");
6.148 +
6.149 + JSONTokener tok = new JSONTokener(r);
6.150 + Object obj;
6.151 + obj = array ? new JSONArray(tok) : new JSONObject(tok);
6.152 + json = convertToArray(obj);
6.153 + } catch (JSONException ex) {
6.154 + Reader r = new InputStreamReader(is, "UTF-8");
6.155 + StringBuilder sb = new StringBuilder();
6.156 + for (;;) {
6.157 + int ch = r.read();
6.158 + if (ch == -1) {
6.159 + break;
6.160 + }
6.161 + sb.append((char)ch);
6.162 + }
6.163 + json = sb.toString();
6.164 + }
6.165 + } catch (IOException ex) {
6.166 + error = ex;
6.167 + LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
6.168 + } finally {
6.169 + Platform.runLater(this);
6.170 + }
6.171 + }
6.172 +
6.173 + private static Object convertToArray(Object o) throws JSONException {
6.174 + if (o instanceof JSONArray) {
6.175 + JSONArray ja = (JSONArray)o;
6.176 + Object[] arr = new Object[ja.length()];
6.177 + for (int i = 0; i < arr.length; i++) {
6.178 + arr[i] = convertToArray(ja.get(i));
6.179 + }
6.180 + return arr;
6.181 + } else if (o instanceof JSONObject) {
6.182 + JSONObject obj = (JSONObject)o;
6.183 + Iterator it = obj.keys();
6.184 + while (it.hasNext()) {
6.185 + String key = (String)it.next();
6.186 + obj.put(key, convertToArray(obj.get(key)));
6.187 + }
6.188 + return obj;
6.189 + } else {
6.190 + return o;
6.191 + }
6.192 + }
6.193 +
6.194 + public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
6.195 + if (jsonObject instanceof JSONObject) {
6.196 + JSONObject obj = (JSONObject)jsonObject;
6.197 + for (int i = 0; i < props.length; i++) {
6.198 + try {
6.199 + values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
6.200 + } catch (JSONException ex) {
6.201 + LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
6.202 + }
6.203 + }
6.204 + }
6.205 + if (jsonObject instanceof JSObject) {
6.206 + JSObject obj = (JSObject)jsonObject;
6.207 + for (int i = 0; i < props.length; i++) {
6.208 + Object val = obj.getMember(props[i]);
6.209 + values[i] = isDefined(val) ? val : null;
6.210 + }
6.211 + }
6.212 + }
6.213 +
6.214 + public static Object parse(InputStream is) throws IOException {
6.215 + try {
6.216 + InputStreamReader r = new InputStreamReader(is, "UTF-8");
6.217 + JSONTokener t = new JSONTokener(r);
6.218 + return new JSONObject(t);
6.219 + } catch (JSONException ex) {
6.220 + throw new IOException(ex);
6.221 + }
6.222 + }
6.223 +
6.224 + @JavaScriptBody(args = { }, body =
6.225 + "var h;"
6.226 + + "if (!!window && !!window.location && !!window.location.href)\n"
6.227 + + " h = window.location.href;\n"
6.228 + + "else "
6.229 + + " h = null;"
6.230 + + "return h;\n"
6.231 + )
6.232 + private static native String findBaseURL();
6.233 +
6.234 + private static boolean isDefined(Object val) {
6.235 + return !"undefined".equals(val);
6.236 + }
6.237 +}
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/ko/fx/src/main/resources/org/apidesign/html/kofx/knockout-2.2.1.js Wed Jun 26 19:57:38 2013 +0200
7.3 @@ -0,0 +1,3594 @@
7.4 +// Knockout JavaScript library v2.2.1
7.5 +// (c) Steven Sanderson - http://knockoutjs.com/
7.6 +// License: MIT (http://www.opensource.org/licenses/mit-license.php)
7.7 +
7.8 +(function(){
7.9 +var DEBUG=true;
7.10 +(function(window,document,navigator,jQuery,undefined){
7.11 +!function(factory) {
7.12 + // Support three module loading scenarios
7.13 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
7.14 + // [1] CommonJS/Node.js
7.15 + var target = module['exports'] || exports; // module.exports is for Node.js
7.16 + factory(target);
7.17 + } else if (typeof define === 'function' && define['amd']) {
7.18 + // [2] AMD anonymous module
7.19 + define(['exports'], factory);
7.20 + } else {
7.21 + // [3] No module loader (plain <script> tag) - put directly in global namespace
7.22 + factory(window['ko'] = {});
7.23 + }
7.24 +}(function(koExports){
7.25 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
7.26 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
7.27 +var ko = typeof koExports !== 'undefined' ? koExports : {};
7.28 +// Google Closure Compiler helpers (used only to make the minified file smaller)
7.29 +ko.exportSymbol = function(koPath, object) {
7.30 + var tokens = koPath.split(".");
7.31 +
7.32 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
7.33 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
7.34 + var target = ko;
7.35 +
7.36 + for (var i = 0; i < tokens.length - 1; i++)
7.37 + target = target[tokens[i]];
7.38 + target[tokens[tokens.length - 1]] = object;
7.39 +};
7.40 +ko.exportProperty = function(owner, publicName, object) {
7.41 + owner[publicName] = object;
7.42 +};
7.43 +ko.version = "2.2.1";
7.44 +
7.45 +ko.exportSymbol('version', ko.version);
7.46 +ko.utils = new (function () {
7.47 + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
7.48 +
7.49 + // 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)
7.50 + var knownEvents = {}, knownEventTypesByEventName = {};
7.51 + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
7.52 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
7.53 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
7.54 + for (var eventType in knownEvents) {
7.55 + var knownEventsForType = knownEvents[eventType];
7.56 + if (knownEventsForType.length) {
7.57 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
7.58 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
7.59 + }
7.60 + }
7.61 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
7.62 +
7.63 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
7.64 + // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
7.65 + // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
7.66 + // If there is a future need to detect specific versions of IE10+, we will amend this.
7.67 + var ieVersion = (function() {
7.68 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
7.69 +
7.70 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
7.71 + while (
7.72 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
7.73 + iElems[0]
7.74 + );
7.75 + return version > 4 ? version : undefined;
7.76 + }());
7.77 + var isIe6 = ieVersion === 6,
7.78 + isIe7 = ieVersion === 7;
7.79 +
7.80 + function isClickOnCheckableElement(element, eventType) {
7.81 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
7.82 + if (eventType.toLowerCase() != "click") return false;
7.83 + var inputType = element.type;
7.84 + return (inputType == "checkbox") || (inputType == "radio");
7.85 + }
7.86 +
7.87 + return {
7.88 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
7.89 +
7.90 + arrayForEach: function (array, action) {
7.91 + for (var i = 0, j = array.length; i < j; i++)
7.92 + action(array[i]);
7.93 + },
7.94 +
7.95 + arrayIndexOf: function (array, item) {
7.96 + if (typeof Array.prototype.indexOf == "function")
7.97 + return Array.prototype.indexOf.call(array, item);
7.98 + for (var i = 0, j = array.length; i < j; i++)
7.99 + if (array[i] === item)
7.100 + return i;
7.101 + return -1;
7.102 + },
7.103 +
7.104 + arrayFirst: function (array, predicate, predicateOwner) {
7.105 + for (var i = 0, j = array.length; i < j; i++)
7.106 + if (predicate.call(predicateOwner, array[i]))
7.107 + return array[i];
7.108 + return null;
7.109 + },
7.110 +
7.111 + arrayRemoveItem: function (array, itemToRemove) {
7.112 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
7.113 + if (index >= 0)
7.114 + array.splice(index, 1);
7.115 + },
7.116 +
7.117 + arrayGetDistinctValues: function (array) {
7.118 + array = array || [];
7.119 + var result = [];
7.120 + for (var i = 0, j = array.length; i < j; i++) {
7.121 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
7.122 + result.push(array[i]);
7.123 + }
7.124 + return result;
7.125 + },
7.126 +
7.127 + arrayMap: function (array, mapping) {
7.128 + array = array || [];
7.129 + var result = [];
7.130 + for (var i = 0, j = array.length; i < j; i++)
7.131 + result.push(mapping(array[i]));
7.132 + return result;
7.133 + },
7.134 +
7.135 + arrayFilter: function (array, predicate) {
7.136 + array = array || [];
7.137 + var result = [];
7.138 + for (var i = 0, j = array.length; i < j; i++)
7.139 + if (predicate(array[i]))
7.140 + result.push(array[i]);
7.141 + return result;
7.142 + },
7.143 +
7.144 + arrayPushAll: function (array, valuesToPush) {
7.145 + if (valuesToPush instanceof Array)
7.146 + array.push.apply(array, valuesToPush);
7.147 + else
7.148 + for (var i = 0, j = valuesToPush.length; i < j; i++)
7.149 + array.push(valuesToPush[i]);
7.150 + return array;
7.151 + },
7.152 +
7.153 + extend: function (target, source) {
7.154 + if (source) {
7.155 + for(var prop in source) {
7.156 + if(source.hasOwnProperty(prop)) {
7.157 + target[prop] = source[prop];
7.158 + }
7.159 + }
7.160 + }
7.161 + return target;
7.162 + },
7.163 +
7.164 + emptyDomNode: function (domNode) {
7.165 + while (domNode.firstChild) {
7.166 + ko.removeNode(domNode.firstChild);
7.167 + }
7.168 + },
7.169 +
7.170 + moveCleanedNodesToContainerElement: function(nodes) {
7.171 + // Ensure it's a real array, as we're about to reparent the nodes and
7.172 + // we don't want the underlying collection to change while we're doing that.
7.173 + var nodesArray = ko.utils.makeArray(nodes);
7.174 +
7.175 + var container = document.createElement('div');
7.176 + for (var i = 0, j = nodesArray.length; i < j; i++) {
7.177 + container.appendChild(ko.cleanNode(nodesArray[i]));
7.178 + }
7.179 + return container;
7.180 + },
7.181 +
7.182 + cloneNodes: function (nodesArray, shouldCleanNodes) {
7.183 + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
7.184 + var clonedNode = nodesArray[i].cloneNode(true);
7.185 + newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
7.186 + }
7.187 + return newNodesArray;
7.188 + },
7.189 +
7.190 + setDomNodeChildren: function (domNode, childNodes) {
7.191 + ko.utils.emptyDomNode(domNode);
7.192 + if (childNodes) {
7.193 + for (var i = 0, j = childNodes.length; i < j; i++)
7.194 + domNode.appendChild(childNodes[i]);
7.195 + }
7.196 + },
7.197 +
7.198 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
7.199 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
7.200 + if (nodesToReplaceArray.length > 0) {
7.201 + var insertionPoint = nodesToReplaceArray[0];
7.202 + var parent = insertionPoint.parentNode;
7.203 + for (var i = 0, j = newNodesArray.length; i < j; i++)
7.204 + parent.insertBefore(newNodesArray[i], insertionPoint);
7.205 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
7.206 + ko.removeNode(nodesToReplaceArray[i]);
7.207 + }
7.208 + }
7.209 + },
7.210 +
7.211 + setOptionNodeSelectionState: function (optionNode, isSelected) {
7.212 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
7.213 + if (ieVersion < 7)
7.214 + optionNode.setAttribute("selected", isSelected);
7.215 + else
7.216 + optionNode.selected = isSelected;
7.217 + },
7.218 +
7.219 + stringTrim: function (string) {
7.220 + return (string || "").replace(stringTrimRegex, "");
7.221 + },
7.222 +
7.223 + stringTokenize: function (string, delimiter) {
7.224 + var result = [];
7.225 + var tokens = (string || "").split(delimiter);
7.226 + for (var i = 0, j = tokens.length; i < j; i++) {
7.227 + var trimmed = ko.utils.stringTrim(tokens[i]);
7.228 + if (trimmed !== "")
7.229 + result.push(trimmed);
7.230 + }
7.231 + return result;
7.232 + },
7.233 +
7.234 + stringStartsWith: function (string, startsWith) {
7.235 + string = string || "";
7.236 + if (startsWith.length > string.length)
7.237 + return false;
7.238 + return string.substring(0, startsWith.length) === startsWith;
7.239 + },
7.240 +
7.241 + domNodeIsContainedBy: function (node, containedByNode) {
7.242 + if (containedByNode.compareDocumentPosition)
7.243 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
7.244 + while (node != null) {
7.245 + if (node == containedByNode)
7.246 + return true;
7.247 + node = node.parentNode;
7.248 + }
7.249 + return false;
7.250 + },
7.251 +
7.252 + domNodeIsAttachedToDocument: function (node) {
7.253 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
7.254 + },
7.255 +
7.256 + tagNameLower: function(element) {
7.257 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
7.258 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
7.259 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
7.260 + return element && element.tagName && element.tagName.toLowerCase();
7.261 + },
7.262 +
7.263 + registerEventHandler: function (element, eventType, handler) {
7.264 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
7.265 + if (!mustUseAttachEvent && typeof jQuery != "undefined") {
7.266 + if (isClickOnCheckableElement(element, eventType)) {
7.267 + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
7.268 + // it toggles the element checked state *after* the click event handlers run, whereas native
7.269 + // click events toggle the checked state *before* the event handler.
7.270 + // Fix this by intecepting the handler and applying the correct checkedness before it runs.
7.271 + var originalHandler = handler;
7.272 + handler = function(event, eventData) {
7.273 + var jQuerySuppliedCheckedState = this.checked;
7.274 + if (eventData)
7.275 + this.checked = eventData.checkedStateBeforeEvent !== true;
7.276 + originalHandler.call(this, event);
7.277 + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
7.278 + };
7.279 + }
7.280 + jQuery(element)['bind'](eventType, handler);
7.281 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
7.282 + element.addEventListener(eventType, handler, false);
7.283 + else if (typeof element.attachEvent != "undefined")
7.284 + element.attachEvent("on" + eventType, function (event) {
7.285 + handler.call(element, event);
7.286 + });
7.287 + else
7.288 + throw new Error("Browser doesn't support addEventListener or attachEvent");
7.289 + },
7.290 +
7.291 + triggerEvent: function (element, eventType) {
7.292 + if (!(element && element.nodeType))
7.293 + throw new Error("element must be a DOM node when calling triggerEvent");
7.294 +
7.295 + if (typeof jQuery != "undefined") {
7.296 + var eventData = [];
7.297 + if (isClickOnCheckableElement(element, eventType)) {
7.298 + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
7.299 + eventData.push({ checkedStateBeforeEvent: element.checked });
7.300 + }
7.301 + jQuery(element)['trigger'](eventType, eventData);
7.302 + } else if (typeof document.createEvent == "function") {
7.303 + if (typeof element.dispatchEvent == "function") {
7.304 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
7.305 + var event = document.createEvent(eventCategory);
7.306 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
7.307 + element.dispatchEvent(event);
7.308 + }
7.309 + else
7.310 + throw new Error("The supplied element doesn't support dispatchEvent");
7.311 + } else if (typeof element.fireEvent != "undefined") {
7.312 + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
7.313 + // so to make it consistent, we'll do it manually here
7.314 + if (isClickOnCheckableElement(element, eventType))
7.315 + element.checked = element.checked !== true;
7.316 + element.fireEvent("on" + eventType);
7.317 + }
7.318 + else
7.319 + throw new Error("Browser doesn't support triggering events");
7.320 + },
7.321 +
7.322 + unwrapObservable: function (value) {
7.323 + return ko.isObservable(value) ? value() : value;
7.324 + },
7.325 +
7.326 + peekObservable: function (value) {
7.327 + return ko.isObservable(value) ? value.peek() : value;
7.328 + },
7.329 +
7.330 + toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
7.331 + if (classNames) {
7.332 + var cssClassNameRegex = /[\w-]+/g,
7.333 + currentClassNames = node.className.match(cssClassNameRegex) || [];
7.334 + ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
7.335 + var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
7.336 + if (indexOfClass >= 0) {
7.337 + if (!shouldHaveClass)
7.338 + currentClassNames.splice(indexOfClass, 1);
7.339 + } else {
7.340 + if (shouldHaveClass)
7.341 + currentClassNames.push(className);
7.342 + }
7.343 + });
7.344 + node.className = currentClassNames.join(" ");
7.345 + }
7.346 + },
7.347 +
7.348 + setTextContent: function(element, textContent) {
7.349 + var value = ko.utils.unwrapObservable(textContent);
7.350 + if ((value === null) || (value === undefined))
7.351 + value = "";
7.352 +
7.353 + if (element.nodeType === 3) {
7.354 + element.data = value;
7.355 + } else {
7.356 + // We need there to be exactly one child: a text node.
7.357 + // If there are no children, more than one, or if it's not a text node,
7.358 + // we'll clear everything and create a single text node.
7.359 + var innerTextNode = ko.virtualElements.firstChild(element);
7.360 + if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
7.361 + ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
7.362 + } else {
7.363 + innerTextNode.data = value;
7.364 + }
7.365 +
7.366 + ko.utils.forceRefresh(element);
7.367 + }
7.368 + },
7.369 +
7.370 + setElementName: function(element, name) {
7.371 + element.name = name;
7.372 +
7.373 + // Workaround IE 6/7 issue
7.374 + // - https://github.com/SteveSanderson/knockout/issues/197
7.375 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
7.376 + if (ieVersion <= 7) {
7.377 + try {
7.378 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
7.379 + }
7.380 + catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
7.381 + }
7.382 + },
7.383 +
7.384 + forceRefresh: function(node) {
7.385 + // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
7.386 + if (ieVersion >= 9) {
7.387 + // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
7.388 + var elem = node.nodeType == 1 ? node : node.parentNode;
7.389 + if (elem.style)
7.390 + elem.style.zoom = elem.style.zoom;
7.391 + }
7.392 + },
7.393 +
7.394 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
7.395 + // 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.
7.396 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
7.397 + if (ieVersion >= 9) {
7.398 + var originalWidth = selectElement.style.width;
7.399 + selectElement.style.width = 0;
7.400 + selectElement.style.width = originalWidth;
7.401 + }
7.402 + },
7.403 +
7.404 + range: function (min, max) {
7.405 + min = ko.utils.unwrapObservable(min);
7.406 + max = ko.utils.unwrapObservable(max);
7.407 + var result = [];
7.408 + for (var i = min; i <= max; i++)
7.409 + result.push(i);
7.410 + return result;
7.411 + },
7.412 +
7.413 + makeArray: function(arrayLikeObject) {
7.414 + var result = [];
7.415 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
7.416 + result.push(arrayLikeObject[i]);
7.417 + };
7.418 + return result;
7.419 + },
7.420 +
7.421 + isIe6 : isIe6,
7.422 + isIe7 : isIe7,
7.423 + ieVersion : ieVersion,
7.424 +
7.425 + getFormFields: function(form, fieldName) {
7.426 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
7.427 + var isMatchingField = (typeof fieldName == 'string')
7.428 + ? function(field) { return field.name === fieldName }
7.429 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
7.430 + var matches = [];
7.431 + for (var i = fields.length - 1; i >= 0; i--) {
7.432 + if (isMatchingField(fields[i]))
7.433 + matches.push(fields[i]);
7.434 + };
7.435 + return matches;
7.436 + },
7.437 +
7.438 + parseJson: function (jsonString) {
7.439 + if (typeof jsonString == "string") {
7.440 + jsonString = ko.utils.stringTrim(jsonString);
7.441 + if (jsonString) {
7.442 + if (window.JSON && window.JSON.parse) // Use native parsing where available
7.443 + return window.JSON.parse(jsonString);
7.444 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
7.445 + }
7.446 + }
7.447 + return null;
7.448 + },
7.449 +
7.450 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
7.451 + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
7.452 + 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");
7.453 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
7.454 + },
7.455 +
7.456 + postJson: function (urlOrForm, data, options) {
7.457 + options = options || {};
7.458 + var params = options['params'] || {};
7.459 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
7.460 + var url = urlOrForm;
7.461 +
7.462 + // If we were given a form, use its 'action' URL and pick out any requested field values
7.463 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
7.464 + var originalForm = urlOrForm;
7.465 + url = originalForm.action;
7.466 + for (var i = includeFields.length - 1; i >= 0; i--) {
7.467 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
7.468 + for (var j = fields.length - 1; j >= 0; j--)
7.469 + params[fields[j].name] = fields[j].value;
7.470 + }
7.471 + }
7.472 +
7.473 + data = ko.utils.unwrapObservable(data);
7.474 + var form = document.createElement("form");
7.475 + form.style.display = "none";
7.476 + form.action = url;
7.477 + form.method = "post";
7.478 + for (var key in data) {
7.479 + var input = document.createElement("input");
7.480 + input.name = key;
7.481 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
7.482 + form.appendChild(input);
7.483 + }
7.484 + for (var key in params) {
7.485 + var input = document.createElement("input");
7.486 + input.name = key;
7.487 + input.value = params[key];
7.488 + form.appendChild(input);
7.489 + }
7.490 + document.body.appendChild(form);
7.491 + options['submitter'] ? options['submitter'](form) : form.submit();
7.492 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
7.493 + }
7.494 + }
7.495 +})();
7.496 +
7.497 +ko.exportSymbol('utils', ko.utils);
7.498 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
7.499 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
7.500 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
7.501 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
7.502 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
7.503 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
7.504 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
7.505 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
7.506 +ko.exportSymbol('utils.extend', ko.utils.extend);
7.507 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
7.508 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
7.509 +ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
7.510 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
7.511 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
7.512 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
7.513 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
7.514 +ko.exportSymbol('utils.range', ko.utils.range);
7.515 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
7.516 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
7.517 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
7.518 +
7.519 +if (!Function.prototype['bind']) {
7.520 + // 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)
7.521 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
7.522 + Function.prototype['bind'] = function (object) {
7.523 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
7.524 + return function () {
7.525 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
7.526 + };
7.527 + };
7.528 +}
7.529 +
7.530 +ko.utils.domData = new (function () {
7.531 + var uniqueId = 0;
7.532 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
7.533 + var dataStore = {};
7.534 + return {
7.535 + get: function (node, key) {
7.536 + var allDataForNode = ko.utils.domData.getAll(node, false);
7.537 + return allDataForNode === undefined ? undefined : allDataForNode[key];
7.538 + },
7.539 + set: function (node, key, value) {
7.540 + if (value === undefined) {
7.541 + // Make sure we don't actually create a new domData key if we are actually deleting a value
7.542 + if (ko.utils.domData.getAll(node, false) === undefined)
7.543 + return;
7.544 + }
7.545 + var allDataForNode = ko.utils.domData.getAll(node, true);
7.546 + allDataForNode[key] = value;
7.547 + },
7.548 + getAll: function (node, createIfNotFound) {
7.549 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
7.550 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
7.551 + if (!hasExistingDataStore) {
7.552 + if (!createIfNotFound)
7.553 + return undefined;
7.554 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
7.555 + dataStore[dataStoreKey] = {};
7.556 + }
7.557 + return dataStore[dataStoreKey];
7.558 + },
7.559 + clear: function (node) {
7.560 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
7.561 + if (dataStoreKey) {
7.562 + delete dataStore[dataStoreKey];
7.563 + node[dataStoreKeyExpandoPropertyName] = null;
7.564 + return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
7.565 + }
7.566 + return false;
7.567 + }
7.568 + }
7.569 +})();
7.570 +
7.571 +ko.exportSymbol('utils.domData', ko.utils.domData);
7.572 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
7.573 +
7.574 +ko.utils.domNodeDisposal = new (function () {
7.575 + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
7.576 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
7.577 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
7.578 +
7.579 + function getDisposeCallbacksCollection(node, createIfNotFound) {
7.580 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
7.581 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
7.582 + allDisposeCallbacks = [];
7.583 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
7.584 + }
7.585 + return allDisposeCallbacks;
7.586 + }
7.587 + function destroyCallbacksCollection(node) {
7.588 + ko.utils.domData.set(node, domDataKey, undefined);
7.589 + }
7.590 +
7.591 + function cleanSingleNode(node) {
7.592 + // Run all the dispose callbacks
7.593 + var callbacks = getDisposeCallbacksCollection(node, false);
7.594 + if (callbacks) {
7.595 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
7.596 + for (var i = 0; i < callbacks.length; i++)
7.597 + callbacks[i](node);
7.598 + }
7.599 +
7.600 + // Also erase the DOM data
7.601 + ko.utils.domData.clear(node);
7.602 +
7.603 + // Special support for jQuery here because it's so commonly used.
7.604 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
7.605 + // so notify it to tear down any resources associated with the node & descendants here.
7.606 + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
7.607 + jQuery['cleanData']([node]);
7.608 +
7.609 + // Also clear any immediate-child comment nodes, as these wouldn't have been found by
7.610 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
7.611 + if (cleanableNodeTypesWithDescendants[node.nodeType])
7.612 + cleanImmediateCommentTypeChildren(node);
7.613 + }
7.614 +
7.615 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
7.616 + var child, nextChild = nodeWithChildren.firstChild;
7.617 + while (child = nextChild) {
7.618 + nextChild = child.nextSibling;
7.619 + if (child.nodeType === 8)
7.620 + cleanSingleNode(child);
7.621 + }
7.622 + }
7.623 +
7.624 + return {
7.625 + addDisposeCallback : function(node, callback) {
7.626 + if (typeof callback != "function")
7.627 + throw new Error("Callback must be a function");
7.628 + getDisposeCallbacksCollection(node, true).push(callback);
7.629 + },
7.630 +
7.631 + removeDisposeCallback : function(node, callback) {
7.632 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
7.633 + if (callbacksCollection) {
7.634 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
7.635 + if (callbacksCollection.length == 0)
7.636 + destroyCallbacksCollection(node);
7.637 + }
7.638 + },
7.639 +
7.640 + cleanNode : function(node) {
7.641 + // First clean this node, where applicable
7.642 + if (cleanableNodeTypes[node.nodeType]) {
7.643 + cleanSingleNode(node);
7.644 +
7.645 + // ... then its descendants, where applicable
7.646 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
7.647 + // Clone the descendants list in case it changes during iteration
7.648 + var descendants = [];
7.649 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
7.650 + for (var i = 0, j = descendants.length; i < j; i++)
7.651 + cleanSingleNode(descendants[i]);
7.652 + }
7.653 + }
7.654 + return node;
7.655 + },
7.656 +
7.657 + removeNode : function(node) {
7.658 + ko.cleanNode(node);
7.659 + if (node.parentNode)
7.660 + node.parentNode.removeChild(node);
7.661 + }
7.662 + }
7.663 +})();
7.664 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
7.665 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
7.666 +ko.exportSymbol('cleanNode', ko.cleanNode);
7.667 +ko.exportSymbol('removeNode', ko.removeNode);
7.668 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
7.669 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
7.670 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
7.671 +(function () {
7.672 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
7.673 +
7.674 + function simpleHtmlParse(html) {
7.675 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
7.676 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
7.677 +
7.678 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
7.679 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
7.680 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
7.681 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
7.682 +
7.683 + // Trim whitespace, otherwise indexOf won't work as expected
7.684 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
7.685 +
7.686 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
7.687 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
7.688 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
7.689 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
7.690 + /* anything else */ [0, "", ""];
7.691 +
7.692 + // Go to html and back, then peel off extra wrappers
7.693 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
7.694 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
7.695 + if (typeof window['innerShiv'] == "function") {
7.696 + div.appendChild(window['innerShiv'](markup));
7.697 + } else {
7.698 + div.innerHTML = markup;
7.699 + }
7.700 +
7.701 + // Move to the right depth
7.702 + while (wrap[0]--)
7.703 + div = div.lastChild;
7.704 +
7.705 + return ko.utils.makeArray(div.lastChild.childNodes);
7.706 + }
7.707 +
7.708 + function jQueryHtmlParse(html) {
7.709 + // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
7.710 + if (jQuery['parseHTML']) {
7.711 + return jQuery['parseHTML'](html);
7.712 + } else {
7.713 + // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
7.714 + var elems = jQuery['clean']([html]);
7.715 +
7.716 + // 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.
7.717 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
7.718 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
7.719 + if (elems && elems[0]) {
7.720 + // Find the top-most parent element that's a direct child of a document fragment
7.721 + var elem = elems[0];
7.722 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
7.723 + elem = elem.parentNode;
7.724 + // ... then detach it
7.725 + if (elem.parentNode)
7.726 + elem.parentNode.removeChild(elem);
7.727 + }
7.728 +
7.729 + return elems;
7.730 + }
7.731 + }
7.732 +
7.733 + ko.utils.parseHtmlFragment = function(html) {
7.734 + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
7.735 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
7.736 + };
7.737 +
7.738 + ko.utils.setHtml = function(node, html) {
7.739 + ko.utils.emptyDomNode(node);
7.740 +
7.741 + // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
7.742 + html = ko.utils.unwrapObservable(html);
7.743 +
7.744 + if ((html !== null) && (html !== undefined)) {
7.745 + if (typeof html != 'string')
7.746 + html = html.toString();
7.747 +
7.748 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
7.749 + // for example <tr> elements which are not normally allowed to exist on their own.
7.750 + // If you've referenced jQuery we'll use that rather than duplicating its code.
7.751 + if (typeof jQuery != 'undefined') {
7.752 + jQuery(node)['html'](html);
7.753 + } else {
7.754 + // ... otherwise, use KO's own parsing logic.
7.755 + var parsedNodes = ko.utils.parseHtmlFragment(html);
7.756 + for (var i = 0; i < parsedNodes.length; i++)
7.757 + node.appendChild(parsedNodes[i]);
7.758 + }
7.759 + }
7.760 + };
7.761 +})();
7.762 +
7.763 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
7.764 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
7.765 +
7.766 +ko.memoization = (function () {
7.767 + var memos = {};
7.768 +
7.769 + function randomMax8HexChars() {
7.770 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
7.771 + }
7.772 + function generateRandomId() {
7.773 + return randomMax8HexChars() + randomMax8HexChars();
7.774 + }
7.775 + function findMemoNodes(rootNode, appendToArray) {
7.776 + if (!rootNode)
7.777 + return;
7.778 + if (rootNode.nodeType == 8) {
7.779 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
7.780 + if (memoId != null)
7.781 + appendToArray.push({ domNode: rootNode, memoId: memoId });
7.782 + } else if (rootNode.nodeType == 1) {
7.783 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
7.784 + findMemoNodes(childNodes[i], appendToArray);
7.785 + }
7.786 + }
7.787 +
7.788 + return {
7.789 + memoize: function (callback) {
7.790 + if (typeof callback != "function")
7.791 + throw new Error("You can only pass a function to ko.memoization.memoize()");
7.792 + var memoId = generateRandomId();
7.793 + memos[memoId] = callback;
7.794 + return "<!--[ko_memo:" + memoId + "]-->";
7.795 + },
7.796 +
7.797 + unmemoize: function (memoId, callbackParams) {
7.798 + var callback = memos[memoId];
7.799 + if (callback === undefined)
7.800 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
7.801 + try {
7.802 + callback.apply(null, callbackParams || []);
7.803 + return true;
7.804 + }
7.805 + finally { delete memos[memoId]; }
7.806 + },
7.807 +
7.808 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
7.809 + var memos = [];
7.810 + findMemoNodes(domNode, memos);
7.811 + for (var i = 0, j = memos.length; i < j; i++) {
7.812 + var node = memos[i].domNode;
7.813 + var combinedParams = [node];
7.814 + if (extraCallbackParamsArray)
7.815 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
7.816 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
7.817 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
7.818 + if (node.parentNode)
7.819 + 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)
7.820 + }
7.821 + },
7.822 +
7.823 + parseMemoText: function (memoText) {
7.824 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
7.825 + return match ? match[1] : null;
7.826 + }
7.827 + };
7.828 +})();
7.829 +
7.830 +ko.exportSymbol('memoization', ko.memoization);
7.831 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
7.832 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
7.833 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
7.834 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
7.835 +ko.extenders = {
7.836 + 'throttle': function(target, timeout) {
7.837 + // Throttling means two things:
7.838 +
7.839 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
7.840 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
7.841 + target['throttleEvaluation'] = timeout;
7.842 +
7.843 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
7.844 + // so the target cannot change value synchronously or faster than a certain rate
7.845 + var writeTimeoutInstance = null;
7.846 + return ko.dependentObservable({
7.847 + 'read': target,
7.848 + 'write': function(value) {
7.849 + clearTimeout(writeTimeoutInstance);
7.850 + writeTimeoutInstance = setTimeout(function() {
7.851 + target(value);
7.852 + }, timeout);
7.853 + }
7.854 + });
7.855 + },
7.856 +
7.857 + 'notify': function(target, notifyWhen) {
7.858 + target["equalityComparer"] = notifyWhen == "always"
7.859 + ? function() { return false } // Treat all values as not equal
7.860 + : ko.observable["fn"]["equalityComparer"];
7.861 + return target;
7.862 + }
7.863 +};
7.864 +
7.865 +function applyExtenders(requestedExtenders) {
7.866 + var target = this;
7.867 + if (requestedExtenders) {
7.868 + for (var key in requestedExtenders) {
7.869 + var extenderHandler = ko.extenders[key];
7.870 + if (typeof extenderHandler == 'function') {
7.871 + target = extenderHandler(target, requestedExtenders[key]);
7.872 + }
7.873 + }
7.874 + }
7.875 + return target;
7.876 +}
7.877 +
7.878 +ko.exportSymbol('extenders', ko.extenders);
7.879 +
7.880 +ko.subscription = function (target, callback, disposeCallback) {
7.881 + this.target = target;
7.882 + this.callback = callback;
7.883 + this.disposeCallback = disposeCallback;
7.884 + ko.exportProperty(this, 'dispose', this.dispose);
7.885 +};
7.886 +ko.subscription.prototype.dispose = function () {
7.887 + this.isDisposed = true;
7.888 + this.disposeCallback();
7.889 +};
7.890 +
7.891 +ko.subscribable = function () {
7.892 + this._subscriptions = {};
7.893 +
7.894 + ko.utils.extend(this, ko.subscribable['fn']);
7.895 + ko.exportProperty(this, 'subscribe', this.subscribe);
7.896 + ko.exportProperty(this, 'extend', this.extend);
7.897 + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
7.898 +}
7.899 +
7.900 +var defaultEvent = "change";
7.901 +
7.902 +ko.subscribable['fn'] = {
7.903 + subscribe: function (callback, callbackTarget, event) {
7.904 + event = event || defaultEvent;
7.905 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
7.906 +
7.907 + var subscription = new ko.subscription(this, boundCallback, function () {
7.908 + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
7.909 + }.bind(this));
7.910 +
7.911 + if (!this._subscriptions[event])
7.912 + this._subscriptions[event] = [];
7.913 + this._subscriptions[event].push(subscription);
7.914 + return subscription;
7.915 + },
7.916 +
7.917 + "notifySubscribers": function (valueToNotify, event) {
7.918 + event = event || defaultEvent;
7.919 + if (this._subscriptions[event]) {
7.920 + ko.dependencyDetection.ignore(function() {
7.921 + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
7.922 + // In case a subscription was disposed during the arrayForEach cycle, check
7.923 + // for isDisposed on each subscription before invoking its callback
7.924 + if (subscription && (subscription.isDisposed !== true))
7.925 + subscription.callback(valueToNotify);
7.926 + });
7.927 + }, this);
7.928 + }
7.929 + },
7.930 +
7.931 + getSubscriptionsCount: function () {
7.932 + var total = 0;
7.933 + for (var eventName in this._subscriptions) {
7.934 + if (this._subscriptions.hasOwnProperty(eventName))
7.935 + total += this._subscriptions[eventName].length;
7.936 + }
7.937 + return total;
7.938 + },
7.939 +
7.940 + extend: applyExtenders
7.941 +};
7.942 +
7.943 +
7.944 +ko.isSubscribable = function (instance) {
7.945 + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
7.946 +};
7.947 +
7.948 +ko.exportSymbol('subscribable', ko.subscribable);
7.949 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
7.950 +
7.951 +ko.dependencyDetection = (function () {
7.952 + var _frames = [];
7.953 +
7.954 + return {
7.955 + begin: function (callback) {
7.956 + _frames.push({ callback: callback, distinctDependencies:[] });
7.957 + },
7.958 +
7.959 + end: function () {
7.960 + _frames.pop();
7.961 + },
7.962 +
7.963 + registerDependency: function (subscribable) {
7.964 + if (!ko.isSubscribable(subscribable))
7.965 + throw new Error("Only subscribable things can act as dependencies");
7.966 + if (_frames.length > 0) {
7.967 + var topFrame = _frames[_frames.length - 1];
7.968 + if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
7.969 + return;
7.970 + topFrame.distinctDependencies.push(subscribable);
7.971 + topFrame.callback(subscribable);
7.972 + }
7.973 + },
7.974 +
7.975 + ignore: function(callback, callbackTarget, callbackArgs) {
7.976 + try {
7.977 + _frames.push(null);
7.978 + return callback.apply(callbackTarget, callbackArgs || []);
7.979 + } finally {
7.980 + _frames.pop();
7.981 + }
7.982 + }
7.983 + };
7.984 +})();
7.985 +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
7.986 +
7.987 +ko.observable = function (initialValue) {
7.988 + var _latestValue = initialValue;
7.989 +
7.990 + function observable() {
7.991 + if (arguments.length > 0) {
7.992 + // Write
7.993 +
7.994 + // Ignore writes if the value hasn't changed
7.995 + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
7.996 + observable.valueWillMutate();
7.997 + _latestValue = arguments[0];
7.998 + if (DEBUG) observable._latestValue = _latestValue;
7.999 + observable.valueHasMutated();
7.1000 + }
7.1001 + return this; // Permits chained assignments
7.1002 + }
7.1003 + else {
7.1004 + // Read
7.1005 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
7.1006 + return _latestValue;
7.1007 + }
7.1008 + }
7.1009 + if (DEBUG) observable._latestValue = _latestValue;
7.1010 + ko.subscribable.call(observable);
7.1011 + observable.peek = function() { return _latestValue };
7.1012 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
7.1013 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
7.1014 + ko.utils.extend(observable, ko.observable['fn']);
7.1015 +
7.1016 + ko.exportProperty(observable, 'peek', observable.peek);
7.1017 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
7.1018 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
7.1019 +
7.1020 + return observable;
7.1021 +}
7.1022 +
7.1023 +ko.observable['fn'] = {
7.1024 + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
7.1025 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
7.1026 + return oldValueIsPrimitive ? (a === b) : false;
7.1027 + }
7.1028 +};
7.1029 +
7.1030 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
7.1031 +ko.observable['fn'][protoProperty] = ko.observable;
7.1032 +
7.1033 +ko.hasPrototype = function(instance, prototype) {
7.1034 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
7.1035 + if (instance[protoProperty] === prototype) return true;
7.1036 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
7.1037 +};
7.1038 +
7.1039 +ko.isObservable = function (instance) {
7.1040 + return ko.hasPrototype(instance, ko.observable);
7.1041 +}
7.1042 +ko.isWriteableObservable = function (instance) {
7.1043 + // Observable
7.1044 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
7.1045 + return true;
7.1046 + // Writeable dependent observable
7.1047 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
7.1048 + return true;
7.1049 + // Anything else
7.1050 + return false;
7.1051 +}
7.1052 +
7.1053 +
7.1054 +ko.exportSymbol('observable', ko.observable);
7.1055 +ko.exportSymbol('isObservable', ko.isObservable);
7.1056 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
7.1057 +ko.observableArray = function (initialValues) {
7.1058 + if (arguments.length == 0) {
7.1059 + // Zero-parameter constructor initializes to empty array
7.1060 + initialValues = [];
7.1061 + }
7.1062 + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
7.1063 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
7.1064 +
7.1065 + var result = ko.observable(initialValues);
7.1066 + ko.utils.extend(result, ko.observableArray['fn']);
7.1067 + return result;
7.1068 +}
7.1069 +
7.1070 +ko.observableArray['fn'] = {
7.1071 + 'remove': function (valueOrPredicate) {
7.1072 + var underlyingArray = this.peek();
7.1073 + var removedValues = [];
7.1074 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
7.1075 + for (var i = 0; i < underlyingArray.length; i++) {
7.1076 + var value = underlyingArray[i];
7.1077 + if (predicate(value)) {
7.1078 + if (removedValues.length === 0) {
7.1079 + this.valueWillMutate();
7.1080 + }
7.1081 + removedValues.push(value);
7.1082 + underlyingArray.splice(i, 1);
7.1083 + i--;
7.1084 + }
7.1085 + }
7.1086 + if (removedValues.length) {
7.1087 + this.valueHasMutated();
7.1088 + }
7.1089 + return removedValues;
7.1090 + },
7.1091 +
7.1092 + 'removeAll': function (arrayOfValues) {
7.1093 + // If you passed zero args, we remove everything
7.1094 + if (arrayOfValues === undefined) {
7.1095 + var underlyingArray = this.peek();
7.1096 + var allValues = underlyingArray.slice(0);
7.1097 + this.valueWillMutate();
7.1098 + underlyingArray.splice(0, underlyingArray.length);
7.1099 + this.valueHasMutated();
7.1100 + return allValues;
7.1101 + }
7.1102 + // If you passed an arg, we interpret it as an array of entries to remove
7.1103 + if (!arrayOfValues)
7.1104 + return [];
7.1105 + return this['remove'](function (value) {
7.1106 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
7.1107 + });
7.1108 + },
7.1109 +
7.1110 + 'destroy': function (valueOrPredicate) {
7.1111 + var underlyingArray = this.peek();
7.1112 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
7.1113 + this.valueWillMutate();
7.1114 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
7.1115 + var value = underlyingArray[i];
7.1116 + if (predicate(value))
7.1117 + underlyingArray[i]["_destroy"] = true;
7.1118 + }
7.1119 + this.valueHasMutated();
7.1120 + },
7.1121 +
7.1122 + 'destroyAll': function (arrayOfValues) {
7.1123 + // If you passed zero args, we destroy everything
7.1124 + if (arrayOfValues === undefined)
7.1125 + return this['destroy'](function() { return true });
7.1126 +
7.1127 + // If you passed an arg, we interpret it as an array of entries to destroy
7.1128 + if (!arrayOfValues)
7.1129 + return [];
7.1130 + return this['destroy'](function (value) {
7.1131 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
7.1132 + });
7.1133 + },
7.1134 +
7.1135 + 'indexOf': function (item) {
7.1136 + var underlyingArray = this();
7.1137 + return ko.utils.arrayIndexOf(underlyingArray, item);
7.1138 + },
7.1139 +
7.1140 + 'replace': function(oldItem, newItem) {
7.1141 + var index = this['indexOf'](oldItem);
7.1142 + if (index >= 0) {
7.1143 + this.valueWillMutate();
7.1144 + this.peek()[index] = newItem;
7.1145 + this.valueHasMutated();
7.1146 + }
7.1147 + }
7.1148 +}
7.1149 +
7.1150 +// Populate ko.observableArray.fn with read/write functions from native arrays
7.1151 +// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
7.1152 +// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
7.1153 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
7.1154 + ko.observableArray['fn'][methodName] = function () {
7.1155 + // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
7.1156 + // (for consistency with mutating regular observables)
7.1157 + var underlyingArray = this.peek();
7.1158 + this.valueWillMutate();
7.1159 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
7.1160 + this.valueHasMutated();
7.1161 + return methodCallResult;
7.1162 + };
7.1163 +});
7.1164 +
7.1165 +// Populate ko.observableArray.fn with read-only functions from native arrays
7.1166 +ko.utils.arrayForEach(["slice"], function (methodName) {
7.1167 + ko.observableArray['fn'][methodName] = function () {
7.1168 + var underlyingArray = this();
7.1169 + return underlyingArray[methodName].apply(underlyingArray, arguments);
7.1170 + };
7.1171 +});
7.1172 +
7.1173 +ko.exportSymbol('observableArray', ko.observableArray);
7.1174 +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
7.1175 + var _latestValue,
7.1176 + _hasBeenEvaluated = false,
7.1177 + _isBeingEvaluated = false,
7.1178 + readFunction = evaluatorFunctionOrOptions;
7.1179 +
7.1180 + if (readFunction && typeof readFunction == "object") {
7.1181 + // Single-parameter syntax - everything is on this "options" param
7.1182 + options = readFunction;
7.1183 + readFunction = options["read"];
7.1184 + } else {
7.1185 + // Multi-parameter syntax - construct the options according to the params passed
7.1186 + options = options || {};
7.1187 + if (!readFunction)
7.1188 + readFunction = options["read"];
7.1189 + }
7.1190 + if (typeof readFunction != "function")
7.1191 + throw new Error("Pass a function that returns the value of the ko.computed");
7.1192 +
7.1193 + function addSubscriptionToDependency(subscribable) {
7.1194 + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
7.1195 + }
7.1196 +
7.1197 + function disposeAllSubscriptionsToDependencies() {
7.1198 + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
7.1199 + subscription.dispose();
7.1200 + });
7.1201 + _subscriptionsToDependencies = [];
7.1202 + }
7.1203 +
7.1204 + function evaluatePossiblyAsync() {
7.1205 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
7.1206 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
7.1207 + clearTimeout(evaluationTimeoutInstance);
7.1208 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
7.1209 + } else
7.1210 + evaluateImmediate();
7.1211 + }
7.1212 +
7.1213 + function evaluateImmediate() {
7.1214 + if (_isBeingEvaluated) {
7.1215 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
7.1216 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
7.1217 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
7.1218 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
7.1219 + return;
7.1220 + }
7.1221 +
7.1222 + // Don't dispose on first evaluation, because the "disposeWhen" callback might
7.1223 + // e.g., dispose when the associated DOM element isn't in the doc, and it's not
7.1224 + // going to be in the doc until *after* the first evaluation
7.1225 + if (_hasBeenEvaluated && disposeWhen()) {
7.1226 + dispose();
7.1227 + return;
7.1228 + }
7.1229 +
7.1230 + _isBeingEvaluated = true;
7.1231 + try {
7.1232 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
7.1233 + // Then, during evaluation, we cross off any that are in fact still being used.
7.1234 + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
7.1235 +
7.1236 + ko.dependencyDetection.begin(function(subscribable) {
7.1237 + var inOld;
7.1238 + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
7.1239 + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
7.1240 + else
7.1241 + addSubscriptionToDependency(subscribable); // Brand new subscription - add it
7.1242 + });
7.1243 +
7.1244 + var newValue = readFunction.call(evaluatorFunctionTarget);
7.1245 +
7.1246 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
7.1247 + for (var i = disposalCandidates.length - 1; i >= 0; i--) {
7.1248 + if (disposalCandidates[i])
7.1249 + _subscriptionsToDependencies.splice(i, 1)[0].dispose();
7.1250 + }
7.1251 + _hasBeenEvaluated = true;
7.1252 +
7.1253 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
7.1254 + _latestValue = newValue;
7.1255 + if (DEBUG) dependentObservable._latestValue = _latestValue;
7.1256 + } finally {
7.1257 + ko.dependencyDetection.end();
7.1258 + }
7.1259 +
7.1260 + dependentObservable["notifySubscribers"](_latestValue);
7.1261 + _isBeingEvaluated = false;
7.1262 + if (!_subscriptionsToDependencies.length)
7.1263 + dispose();
7.1264 + }
7.1265 +
7.1266 + function dependentObservable() {
7.1267 + if (arguments.length > 0) {
7.1268 + if (typeof writeFunction === "function") {
7.1269 + // Writing a value
7.1270 + writeFunction.apply(evaluatorFunctionTarget, arguments);
7.1271 + } else {
7.1272 + 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.");
7.1273 + }
7.1274 + return this; // Permits chained assignments
7.1275 + } else {
7.1276 + // Reading the value
7.1277 + if (!_hasBeenEvaluated)
7.1278 + evaluateImmediate();
7.1279 + ko.dependencyDetection.registerDependency(dependentObservable);
7.1280 + return _latestValue;
7.1281 + }
7.1282 + }
7.1283 +
7.1284 + function peek() {
7.1285 + if (!_hasBeenEvaluated)
7.1286 + evaluateImmediate();
7.1287 + return _latestValue;
7.1288 + }
7.1289 +
7.1290 + function isActive() {
7.1291 + return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
7.1292 + }
7.1293 +
7.1294 + // By here, "options" is always non-null
7.1295 + var writeFunction = options["write"],
7.1296 + disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
7.1297 + disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
7.1298 + dispose = disposeAllSubscriptionsToDependencies,
7.1299 + _subscriptionsToDependencies = [],
7.1300 + evaluationTimeoutInstance = null;
7.1301 +
7.1302 + if (!evaluatorFunctionTarget)
7.1303 + evaluatorFunctionTarget = options["owner"];
7.1304 +
7.1305 + dependentObservable.peek = peek;
7.1306 + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
7.1307 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
7.1308 + dependentObservable.dispose = function () { dispose(); };
7.1309 + dependentObservable.isActive = isActive;
7.1310 + dependentObservable.valueHasMutated = function() {
7.1311 + _hasBeenEvaluated = false;
7.1312 + evaluateImmediate();
7.1313 + };
7.1314 +
7.1315 + ko.subscribable.call(dependentObservable);
7.1316 + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
7.1317 +
7.1318 + ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
7.1319 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
7.1320 + ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
7.1321 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
7.1322 +
7.1323 + // Evaluate, unless deferEvaluation is true
7.1324 + if (options['deferEvaluation'] !== true)
7.1325 + evaluateImmediate();
7.1326 +
7.1327 + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
7.1328 + // But skip if isActive is false (there will never be any dependencies to dispose).
7.1329 + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
7.1330 + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
7.1331 + if (disposeWhenNodeIsRemoved && isActive()) {
7.1332 + dispose = function() {
7.1333 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
7.1334 + disposeAllSubscriptionsToDependencies();
7.1335 + };
7.1336 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
7.1337 + var existingDisposeWhenFunction = disposeWhen;
7.1338 + disposeWhen = function () {
7.1339 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
7.1340 + }
7.1341 + }
7.1342 +
7.1343 + return dependentObservable;
7.1344 +};
7.1345 +
7.1346 +ko.isComputed = function(instance) {
7.1347 + return ko.hasPrototype(instance, ko.dependentObservable);
7.1348 +};
7.1349 +
7.1350 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
7.1351 +ko.dependentObservable[protoProp] = ko.observable;
7.1352 +
7.1353 +ko.dependentObservable['fn'] = {};
7.1354 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
7.1355 +
7.1356 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
7.1357 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
7.1358 +ko.exportSymbol('isComputed', ko.isComputed);
7.1359 +
7.1360 +(function() {
7.1361 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
7.1362 +
7.1363 + ko.toJS = function(rootObject) {
7.1364 + if (arguments.length == 0)
7.1365 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
7.1366 +
7.1367 + // We just unwrap everything at every level in the object graph
7.1368 + return mapJsObjectGraph(rootObject, function(valueToMap) {
7.1369 + // Loop because an observable's value might in turn be another observable wrapper
7.1370 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
7.1371 + valueToMap = valueToMap();
7.1372 + return valueToMap;
7.1373 + });
7.1374 + };
7.1375 +
7.1376 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
7.1377 + var plainJavaScriptObject = ko.toJS(rootObject);
7.1378 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
7.1379 + };
7.1380 +
7.1381 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
7.1382 + visitedObjects = visitedObjects || new objectLookup();
7.1383 +
7.1384 + rootObject = mapInputCallback(rootObject);
7.1385 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
7.1386 + if (!canHaveProperties)
7.1387 + return rootObject;
7.1388 +
7.1389 + var outputProperties = rootObject instanceof Array ? [] : {};
7.1390 + visitedObjects.save(rootObject, outputProperties);
7.1391 +
7.1392 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
7.1393 + var propertyValue = mapInputCallback(rootObject[indexer]);
7.1394 +
7.1395 + switch (typeof propertyValue) {
7.1396 + case "boolean":
7.1397 + case "number":
7.1398 + case "string":
7.1399 + case "function":
7.1400 + outputProperties[indexer] = propertyValue;
7.1401 + break;
7.1402 + case "object":
7.1403 + case "undefined":
7.1404 + var previouslyMappedValue = visitedObjects.get(propertyValue);
7.1405 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
7.1406 + ? previouslyMappedValue
7.1407 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
7.1408 + break;
7.1409 + }
7.1410 + });
7.1411 +
7.1412 + return outputProperties;
7.1413 + }
7.1414 +
7.1415 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
7.1416 + if (rootObject instanceof Array) {
7.1417 + for (var i = 0; i < rootObject.length; i++)
7.1418 + visitorCallback(i);
7.1419 +
7.1420 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
7.1421 + if (typeof rootObject['toJSON'] == 'function')
7.1422 + visitorCallback('toJSON');
7.1423 + } else {
7.1424 + for (var propertyName in rootObject)
7.1425 + visitorCallback(propertyName);
7.1426 + }
7.1427 + };
7.1428 +
7.1429 + function objectLookup() {
7.1430 + var keys = [];
7.1431 + var values = [];
7.1432 + this.save = function(key, value) {
7.1433 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
7.1434 + if (existingIndex >= 0)
7.1435 + values[existingIndex] = value;
7.1436 + else {
7.1437 + keys.push(key);
7.1438 + values.push(value);
7.1439 + }
7.1440 + };
7.1441 + this.get = function(key) {
7.1442 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
7.1443 + return (existingIndex >= 0) ? values[existingIndex] : undefined;
7.1444 + };
7.1445 + };
7.1446 +})();
7.1447 +
7.1448 +ko.exportSymbol('toJS', ko.toJS);
7.1449 +ko.exportSymbol('toJSON', ko.toJSON);
7.1450 +(function () {
7.1451 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
7.1452 +
7.1453 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
7.1454 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
7.1455 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
7.1456 + ko.selectExtensions = {
7.1457 + readValue : function(element) {
7.1458 + switch (ko.utils.tagNameLower(element)) {
7.1459 + case 'option':
7.1460 + if (element[hasDomDataExpandoProperty] === true)
7.1461 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
7.1462 + return ko.utils.ieVersion <= 7
7.1463 + ? (element.getAttributeNode('value').specified ? element.value : element.text)
7.1464 + : element.value;
7.1465 + case 'select':
7.1466 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
7.1467 + default:
7.1468 + return element.value;
7.1469 + }
7.1470 + },
7.1471 +
7.1472 + writeValue: function(element, value) {
7.1473 + switch (ko.utils.tagNameLower(element)) {
7.1474 + case 'option':
7.1475 + switch(typeof value) {
7.1476 + case "string":
7.1477 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
7.1478 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
7.1479 + delete element[hasDomDataExpandoProperty];
7.1480 + }
7.1481 + element.value = value;
7.1482 + break;
7.1483 + default:
7.1484 + // Store arbitrary object using DomData
7.1485 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
7.1486 + element[hasDomDataExpandoProperty] = true;
7.1487 +
7.1488 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
7.1489 + element.value = typeof value === "number" ? value : "";
7.1490 + break;
7.1491 + }
7.1492 + break;
7.1493 + case 'select':
7.1494 + for (var i = element.options.length - 1; i >= 0; i--) {
7.1495 + if (ko.selectExtensions.readValue(element.options[i]) == value) {
7.1496 + element.selectedIndex = i;
7.1497 + break;
7.1498 + }
7.1499 + }
7.1500 + break;
7.1501 + default:
7.1502 + if ((value === null) || (value === undefined))
7.1503 + value = "";
7.1504 + element.value = value;
7.1505 + break;
7.1506 + }
7.1507 + }
7.1508 + };
7.1509 +})();
7.1510 +
7.1511 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
7.1512 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
7.1513 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
7.1514 +ko.expressionRewriting = (function () {
7.1515 + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
7.1516 + var javaScriptReservedWords = ["true", "false"];
7.1517 +
7.1518 + // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
7.1519 + // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
7.1520 + var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
7.1521 +
7.1522 + function restoreTokens(string, tokens) {
7.1523 + var prevValue = null;
7.1524 + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
7.1525 + prevValue = string;
7.1526 + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
7.1527 + return tokens[tokenIndex];
7.1528 + });
7.1529 + }
7.1530 + return string;
7.1531 + }
7.1532 +
7.1533 + function getWriteableValue(expression) {
7.1534 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
7.1535 + return false;
7.1536 + var match = expression.match(javaScriptAssignmentTarget);
7.1537 + return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
7.1538 + }
7.1539 +
7.1540 + function ensureQuoted(key) {
7.1541 + var trimmedKey = ko.utils.stringTrim(key);
7.1542 + switch (trimmedKey.length && trimmedKey.charAt(0)) {
7.1543 + case "'":
7.1544 + case '"':
7.1545 + return key;
7.1546 + default:
7.1547 + return "'" + trimmedKey + "'";
7.1548 + }
7.1549 + }
7.1550 +
7.1551 + return {
7.1552 + bindingRewriteValidators: [],
7.1553 +
7.1554 + parseObjectLiteral: function(objectLiteralString) {
7.1555 + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
7.1556 + // that is sufficient just to split an object literal string into a set of top-level key-value pairs
7.1557 +
7.1558 + var str = ko.utils.stringTrim(objectLiteralString);
7.1559 + if (str.length < 3)
7.1560 + return [];
7.1561 + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
7.1562 + str = str.substring(1, str.length - 1);
7.1563 +
7.1564 + // Pull out any string literals and regex literals
7.1565 + var tokens = [];
7.1566 + var tokenStart = null, tokenEndChar;
7.1567 + for (var position = 0; position < str.length; position++) {
7.1568 + var c = str.charAt(position);
7.1569 + if (tokenStart === null) {
7.1570 + switch (c) {
7.1571 + case '"':
7.1572 + case "'":
7.1573 + case "/":
7.1574 + tokenStart = position;
7.1575 + tokenEndChar = c;
7.1576 + break;
7.1577 + }
7.1578 + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
7.1579 + var token = str.substring(tokenStart, position + 1);
7.1580 + tokens.push(token);
7.1581 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
7.1582 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
7.1583 + position -= (token.length - replacement.length);
7.1584 + tokenStart = null;
7.1585 + }
7.1586 + }
7.1587 +
7.1588 + // Next pull out balanced paren, brace, and bracket blocks
7.1589 + tokenStart = null;
7.1590 + tokenEndChar = null;
7.1591 + var tokenDepth = 0, tokenStartChar = null;
7.1592 + for (var position = 0; position < str.length; position++) {
7.1593 + var c = str.charAt(position);
7.1594 + if (tokenStart === null) {
7.1595 + switch (c) {
7.1596 + case "{": tokenStart = position; tokenStartChar = c;
7.1597 + tokenEndChar = "}";
7.1598 + break;
7.1599 + case "(": tokenStart = position; tokenStartChar = c;
7.1600 + tokenEndChar = ")";
7.1601 + break;
7.1602 + case "[": tokenStart = position; tokenStartChar = c;
7.1603 + tokenEndChar = "]";
7.1604 + break;
7.1605 + }
7.1606 + }
7.1607 +
7.1608 + if (c === tokenStartChar)
7.1609 + tokenDepth++;
7.1610 + else if (c === tokenEndChar) {
7.1611 + tokenDepth--;
7.1612 + if (tokenDepth === 0) {
7.1613 + var token = str.substring(tokenStart, position + 1);
7.1614 + tokens.push(token);
7.1615 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
7.1616 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
7.1617 + position -= (token.length - replacement.length);
7.1618 + tokenStart = null;
7.1619 + }
7.1620 + }
7.1621 + }
7.1622 +
7.1623 + // Now we can safely split on commas to get the key/value pairs
7.1624 + var result = [];
7.1625 + var keyValuePairs = str.split(",");
7.1626 + for (var i = 0, j = keyValuePairs.length; i < j; i++) {
7.1627 + var pair = keyValuePairs[i];
7.1628 + var colonPos = pair.indexOf(":");
7.1629 + if ((colonPos > 0) && (colonPos < pair.length - 1)) {
7.1630 + var key = pair.substring(0, colonPos);
7.1631 + var value = pair.substring(colonPos + 1);
7.1632 + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
7.1633 + } else {
7.1634 + result.push({ 'unknown': restoreTokens(pair, tokens) });
7.1635 + }
7.1636 + }
7.1637 + return result;
7.1638 + },
7.1639 +
7.1640 + preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
7.1641 + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
7.1642 + ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
7.1643 + : objectLiteralStringOrKeyValueArray;
7.1644 + var resultStrings = [], propertyAccessorResultStrings = [];
7.1645 +
7.1646 + var keyValueEntry;
7.1647 + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
7.1648 + if (resultStrings.length > 0)
7.1649 + resultStrings.push(",");
7.1650 +
7.1651 + if (keyValueEntry['key']) {
7.1652 + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
7.1653 + resultStrings.push(quotedKey);
7.1654 + resultStrings.push(":");
7.1655 + resultStrings.push(val);
7.1656 +
7.1657 + if (val = getWriteableValue(ko.utils.stringTrim(val))) {
7.1658 + if (propertyAccessorResultStrings.length > 0)
7.1659 + propertyAccessorResultStrings.push(", ");
7.1660 + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
7.1661 + }
7.1662 + } else if (keyValueEntry['unknown']) {
7.1663 + resultStrings.push(keyValueEntry['unknown']);
7.1664 + }
7.1665 + }
7.1666 +
7.1667 + var combinedResult = resultStrings.join("");
7.1668 + if (propertyAccessorResultStrings.length > 0) {
7.1669 + var allPropertyAccessors = propertyAccessorResultStrings.join("");
7.1670 + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
7.1671 + }
7.1672 +
7.1673 + return combinedResult;
7.1674 + },
7.1675 +
7.1676 + keyValueArrayContainsKey: function(keyValueArray, key) {
7.1677 + for (var i = 0; i < keyValueArray.length; i++)
7.1678 + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
7.1679 + return true;
7.1680 + return false;
7.1681 + },
7.1682 +
7.1683 + // Internal, private KO utility for updating model properties from within bindings
7.1684 + // property: If the property being updated is (or might be) an observable, pass it here
7.1685 + // If it turns out to be a writable observable, it will be written to directly
7.1686 + // allBindingsAccessor: All bindings in the current execution context.
7.1687 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
7.1688 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
7.1689 + // value: The value to be written
7.1690 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
7.1691 + // it is !== existing value on that writable observable
7.1692 + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
7.1693 + if (!property || !ko.isWriteableObservable(property)) {
7.1694 + var propWriters = allBindingsAccessor()['_ko_property_writers'];
7.1695 + if (propWriters && propWriters[key])
7.1696 + propWriters[key](value);
7.1697 + } else if (!checkIfDifferent || property.peek() !== value) {
7.1698 + property(value);
7.1699 + }
7.1700 + }
7.1701 + };
7.1702 +})();
7.1703 +
7.1704 +ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
7.1705 +ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
7.1706 +ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
7.1707 +ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
7.1708 +
7.1709 +// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
7.1710 +// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
7.1711 +ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
7.1712 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
7.1713 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
7.1714 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
7.1715 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
7.1716 + // of that virtual hierarchy
7.1717 + //
7.1718 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
7.1719 + // without having to scatter special cases all over the binding and templating code.
7.1720 +
7.1721 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
7.1722 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
7.1723 + // So, use node.text where available, and node.nodeValue elsewhere
7.1724 + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
7.1725 +
7.1726 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
7.1727 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
7.1728 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
7.1729 +
7.1730 + function isStartComment(node) {
7.1731 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
7.1732 + }
7.1733 +
7.1734 + function isEndComment(node) {
7.1735 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
7.1736 + }
7.1737 +
7.1738 + function getVirtualChildren(startComment, allowUnbalanced) {
7.1739 + var currentNode = startComment;
7.1740 + var depth = 1;
7.1741 + var children = [];
7.1742 + while (currentNode = currentNode.nextSibling) {
7.1743 + if (isEndComment(currentNode)) {
7.1744 + depth--;
7.1745 + if (depth === 0)
7.1746 + return children;
7.1747 + }
7.1748 +
7.1749 + children.push(currentNode);
7.1750 +
7.1751 + if (isStartComment(currentNode))
7.1752 + depth++;
7.1753 + }
7.1754 + if (!allowUnbalanced)
7.1755 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
7.1756 + return null;
7.1757 + }
7.1758 +
7.1759 + function getMatchingEndComment(startComment, allowUnbalanced) {
7.1760 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
7.1761 + if (allVirtualChildren) {
7.1762 + if (allVirtualChildren.length > 0)
7.1763 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
7.1764 + return startComment.nextSibling;
7.1765 + } else
7.1766 + return null; // Must have no matching end comment, and allowUnbalanced is true
7.1767 + }
7.1768 +
7.1769 + function getUnbalancedChildTags(node) {
7.1770 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
7.1771 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
7.1772 + var childNode = node.firstChild, captureRemaining = null;
7.1773 + if (childNode) {
7.1774 + do {
7.1775 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
7.1776 + captureRemaining.push(childNode);
7.1777 + else if (isStartComment(childNode)) {
7.1778 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
7.1779 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
7.1780 + childNode = matchingEndComment;
7.1781 + else
7.1782 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
7.1783 + } else if (isEndComment(childNode)) {
7.1784 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
7.1785 + }
7.1786 + } while (childNode = childNode.nextSibling);
7.1787 + }
7.1788 + return captureRemaining;
7.1789 + }
7.1790 +
7.1791 + ko.virtualElements = {
7.1792 + allowedBindings: {},
7.1793 +
7.1794 + childNodes: function(node) {
7.1795 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
7.1796 + },
7.1797 +
7.1798 + emptyNode: function(node) {
7.1799 + if (!isStartComment(node))
7.1800 + ko.utils.emptyDomNode(node);
7.1801 + else {
7.1802 + var virtualChildren = ko.virtualElements.childNodes(node);
7.1803 + for (var i = 0, j = virtualChildren.length; i < j; i++)
7.1804 + ko.removeNode(virtualChildren[i]);
7.1805 + }
7.1806 + },
7.1807 +
7.1808 + setDomNodeChildren: function(node, childNodes) {
7.1809 + if (!isStartComment(node))
7.1810 + ko.utils.setDomNodeChildren(node, childNodes);
7.1811 + else {
7.1812 + ko.virtualElements.emptyNode(node);
7.1813 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
7.1814 + for (var i = 0, j = childNodes.length; i < j; i++)
7.1815 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
7.1816 + }
7.1817 + },
7.1818 +
7.1819 + prepend: function(containerNode, nodeToPrepend) {
7.1820 + if (!isStartComment(containerNode)) {
7.1821 + if (containerNode.firstChild)
7.1822 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
7.1823 + else
7.1824 + containerNode.appendChild(nodeToPrepend);
7.1825 + } else {
7.1826 + // Start comments must always have a parent and at least one following sibling (the end comment)
7.1827 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
7.1828 + }
7.1829 + },
7.1830 +
7.1831 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
7.1832 + if (!insertAfterNode) {
7.1833 + ko.virtualElements.prepend(containerNode, nodeToInsert);
7.1834 + } else if (!isStartComment(containerNode)) {
7.1835 + // Insert after insertion point
7.1836 + if (insertAfterNode.nextSibling)
7.1837 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
7.1838 + else
7.1839 + containerNode.appendChild(nodeToInsert);
7.1840 + } else {
7.1841 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
7.1842 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
7.1843 + }
7.1844 + },
7.1845 +
7.1846 + firstChild: function(node) {
7.1847 + if (!isStartComment(node))
7.1848 + return node.firstChild;
7.1849 + if (!node.nextSibling || isEndComment(node.nextSibling))
7.1850 + return null;
7.1851 + return node.nextSibling;
7.1852 + },
7.1853 +
7.1854 + nextSibling: function(node) {
7.1855 + if (isStartComment(node))
7.1856 + node = getMatchingEndComment(node);
7.1857 + if (node.nextSibling && isEndComment(node.nextSibling))
7.1858 + return null;
7.1859 + return node.nextSibling;
7.1860 + },
7.1861 +
7.1862 + virtualNodeBindingValue: function(node) {
7.1863 + var regexMatch = isStartComment(node);
7.1864 + return regexMatch ? regexMatch[1] : null;
7.1865 + },
7.1866 +
7.1867 + normaliseVirtualElementDomStructure: function(elementVerified) {
7.1868 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
7.1869 + // (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
7.1870 + // that are direct descendants of <ul> into the preceding <li>)
7.1871 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
7.1872 + return;
7.1873 +
7.1874 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
7.1875 + // must be intended to appear *after* that child, so move them there.
7.1876 + var childNode = elementVerified.firstChild;
7.1877 + if (childNode) {
7.1878 + do {
7.1879 + if (childNode.nodeType === 1) {
7.1880 + var unbalancedTags = getUnbalancedChildTags(childNode);
7.1881 + if (unbalancedTags) {
7.1882 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
7.1883 + var nodeToInsertBefore = childNode.nextSibling;
7.1884 + for (var i = 0; i < unbalancedTags.length; i++) {
7.1885 + if (nodeToInsertBefore)
7.1886 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
7.1887 + else
7.1888 + elementVerified.appendChild(unbalancedTags[i]);
7.1889 + }
7.1890 + }
7.1891 + }
7.1892 + } while (childNode = childNode.nextSibling);
7.1893 + }
7.1894 + }
7.1895 + };
7.1896 +})();
7.1897 +ko.exportSymbol('virtualElements', ko.virtualElements);
7.1898 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
7.1899 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
7.1900 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
7.1901 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
7.1902 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
7.1903 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
7.1904 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
7.1905 +(function() {
7.1906 + var defaultBindingAttributeName = "data-bind";
7.1907 +
7.1908 + ko.bindingProvider = function() {
7.1909 + this.bindingCache = {};
7.1910 + };
7.1911 +
7.1912 + ko.utils.extend(ko.bindingProvider.prototype, {
7.1913 + 'nodeHasBindings': function(node) {
7.1914 + switch (node.nodeType) {
7.1915 + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
7.1916 + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
7.1917 + default: return false;
7.1918 + }
7.1919 + },
7.1920 +
7.1921 + 'getBindings': function(node, bindingContext) {
7.1922 + var bindingsString = this['getBindingsString'](node, bindingContext);
7.1923 + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
7.1924 + },
7.1925 +
7.1926 + // The following function is only used internally by this default provider.
7.1927 + // It's not part of the interface definition for a general binding provider.
7.1928 + 'getBindingsString': function(node, bindingContext) {
7.1929 + switch (node.nodeType) {
7.1930 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
7.1931 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
7.1932 + default: return null;
7.1933 + }
7.1934 + },
7.1935 +
7.1936 + // The following function is only used internally by this default provider.
7.1937 + // It's not part of the interface definition for a general binding provider.
7.1938 + 'parseBindingsString': function(bindingsString, bindingContext, node) {
7.1939 + try {
7.1940 + var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
7.1941 + return bindingFunction(bindingContext, node);
7.1942 + } catch (ex) {
7.1943 + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
7.1944 + }
7.1945 + }
7.1946 + });
7.1947 +
7.1948 + ko.bindingProvider['instance'] = new ko.bindingProvider();
7.1949 +
7.1950 + function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
7.1951 + var cacheKey = bindingsString;
7.1952 + return cache[cacheKey]
7.1953 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
7.1954 + }
7.1955 +
7.1956 + function createBindingsStringEvaluator(bindingsString) {
7.1957 + // Build the source for a function that evaluates "expression"
7.1958 + // For each scope variable, add an extra level of "with" nesting
7.1959 + // Example result: with(sc1) { with(sc0) { return (expression) } }
7.1960 + var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
7.1961 + functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
7.1962 + return new Function("$context", "$element", functionBody);
7.1963 + }
7.1964 +})();
7.1965 +
7.1966 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
7.1967 +(function () {
7.1968 + ko.bindingHandlers = {};
7.1969 +
7.1970 + ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
7.1971 + if (parentBindingContext) {
7.1972 + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
7.1973 + this['$parentContext'] = parentBindingContext;
7.1974 + this['$parent'] = parentBindingContext['$data'];
7.1975 + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
7.1976 + this['$parents'].unshift(this['$parent']);
7.1977 + } else {
7.1978 + this['$parents'] = [];
7.1979 + this['$root'] = dataItem;
7.1980 + // Export 'ko' in the binding context so it will be available in bindings and templates
7.1981 + // even if 'ko' isn't exported as a global, such as when using an AMD loader.
7.1982 + // See https://github.com/SteveSanderson/knockout/issues/490
7.1983 + this['ko'] = ko;
7.1984 + }
7.1985 + this['$data'] = dataItem;
7.1986 + if (dataItemAlias)
7.1987 + this[dataItemAlias] = dataItem;
7.1988 + }
7.1989 + ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
7.1990 + return new ko.bindingContext(dataItem, this, dataItemAlias);
7.1991 + };
7.1992 + ko.bindingContext.prototype['extend'] = function(properties) {
7.1993 + var clone = ko.utils.extend(new ko.bindingContext(), this);
7.1994 + return ko.utils.extend(clone, properties);
7.1995 + };
7.1996 +
7.1997 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
7.1998 + var validator = ko.virtualElements.allowedBindings[bindingName];
7.1999 + if (!validator)
7.2000 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
7.2001 + }
7.2002 +
7.2003 + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
7.2004 + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
7.2005 + while (currentChild = nextInQueue) {
7.2006 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
7.2007 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
7.2008 + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
7.2009 + }
7.2010 + }
7.2011 +
7.2012 + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
7.2013 + var shouldBindDescendants = true;
7.2014 +
7.2015 + // Perf optimisation: Apply bindings only if...
7.2016 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
7.2017 + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
7.2018 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
7.2019 + var isElement = (nodeVerified.nodeType === 1);
7.2020 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
7.2021 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
7.2022 +
7.2023 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
7.2024 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
7.2025 + if (shouldApplyBindings)
7.2026 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
7.2027 +
7.2028 + if (shouldBindDescendants) {
7.2029 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
7.2030 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
7.2031 + // hence bindingContextsMayDifferFromDomParentElement is false
7.2032 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
7.2033 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
7.2034 + // hence bindingContextsMayDifferFromDomParentElement is true
7.2035 + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
7.2036 + }
7.2037 + }
7.2038 +
7.2039 + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
7.2040 + // Need to be sure that inits are only run once, and updates never run until all the inits have been run
7.2041 + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
7.2042 +
7.2043 + // Each time the dependentObservable is evaluated (after data changes),
7.2044 + // the binding attribute is reparsed so that it can pick out the correct
7.2045 + // model properties in the context of the changed data.
7.2046 + // DOM event callbacks need to be able to access this changed data,
7.2047 + // so we need a single parsedBindings variable (shared by all callbacks
7.2048 + // associated with this node's bindings) that all the closures can access.
7.2049 + var parsedBindings;
7.2050 + function makeValueAccessor(bindingKey) {
7.2051 + return function () { return parsedBindings[bindingKey] }
7.2052 + }
7.2053 + function parsedBindingsAccessor() {
7.2054 + return parsedBindings;
7.2055 + }
7.2056 +
7.2057 + var bindingHandlerThatControlsDescendantBindings;
7.2058 + ko.dependentObservable(
7.2059 + function () {
7.2060 + // Ensure we have a nonnull binding context to work with
7.2061 + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
7.2062 + ? viewModelOrBindingContext
7.2063 + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
7.2064 + var viewModel = bindingContextInstance['$data'];
7.2065 +
7.2066 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
7.2067 + // we can easily recover it just by scanning up the node's ancestors in the DOM
7.2068 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
7.2069 + if (bindingContextMayDifferFromDomParentElement)
7.2070 + ko.storedBindingContextForNode(node, bindingContextInstance);
7.2071 +
7.2072 + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
7.2073 + var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
7.2074 + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
7.2075 +
7.2076 + if (parsedBindings) {
7.2077 + // First run all the inits, so bindings can register for notification on changes
7.2078 + if (initPhase === 0) {
7.2079 + initPhase = 1;
7.2080 + for (var bindingKey in parsedBindings) {
7.2081 + var binding = ko.bindingHandlers[bindingKey];
7.2082 + if (binding && node.nodeType === 8)
7.2083 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
7.2084 +
7.2085 + if (binding && typeof binding["init"] == "function") {
7.2086 + var handlerInitFn = binding["init"];
7.2087 + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
7.2088 +
7.2089 + // If this binding handler claims to control descendant bindings, make a note of this
7.2090 + if (initResult && initResult['controlsDescendantBindings']) {
7.2091 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
7.2092 + 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.");
7.2093 + bindingHandlerThatControlsDescendantBindings = bindingKey;
7.2094 + }
7.2095 + }
7.2096 + }
7.2097 + initPhase = 2;
7.2098 + }
7.2099 +
7.2100 + // ... then run all the updates, which might trigger changes even on the first evaluation
7.2101 + if (initPhase === 2) {
7.2102 + for (var bindingKey in parsedBindings) {
7.2103 + var binding = ko.bindingHandlers[bindingKey];
7.2104 + if (binding && typeof binding["update"] == "function") {
7.2105 + var handlerUpdateFn = binding["update"];
7.2106 + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
7.2107 + }
7.2108 + }
7.2109 + }
7.2110 + }
7.2111 + },
7.2112 + null,
7.2113 + { disposeWhenNodeIsRemoved : node }
7.2114 + );
7.2115 +
7.2116 + return {
7.2117 + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
7.2118 + };
7.2119 + };
7.2120 +
7.2121 + var storedBindingContextDomDataKey = "__ko_bindingContext__";
7.2122 + ko.storedBindingContextForNode = function (node, bindingContext) {
7.2123 + if (arguments.length == 2)
7.2124 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
7.2125 + else
7.2126 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
7.2127 + }
7.2128 +
7.2129 + ko.applyBindingsToNode = function (node, bindings, viewModel) {
7.2130 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
7.2131 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
7.2132 + return applyBindingsToNodeInternal(node, bindings, viewModel, true);
7.2133 + };
7.2134 +
7.2135 + ko.applyBindingsToDescendants = function(viewModel, rootNode) {
7.2136 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
7.2137 + applyBindingsToDescendantsInternal(viewModel, rootNode, true);
7.2138 + };
7.2139 +
7.2140 + ko.applyBindings = function (viewModel, rootNode) {
7.2141 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
7.2142 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
7.2143 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
7.2144 +
7.2145 + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
7.2146 + };
7.2147 +
7.2148 + // Retrieving binding context from arbitrary nodes
7.2149 + ko.contextFor = function(node) {
7.2150 + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
7.2151 + switch (node.nodeType) {
7.2152 + case 1:
7.2153 + case 8:
7.2154 + var context = ko.storedBindingContextForNode(node);
7.2155 + if (context) return context;
7.2156 + if (node.parentNode) return ko.contextFor(node.parentNode);
7.2157 + break;
7.2158 + }
7.2159 + return undefined;
7.2160 + };
7.2161 + ko.dataFor = function(node) {
7.2162 + var context = ko.contextFor(node);
7.2163 + return context ? context['$data'] : undefined;
7.2164 + };
7.2165 +
7.2166 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
7.2167 + ko.exportSymbol('applyBindings', ko.applyBindings);
7.2168 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
7.2169 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
7.2170 + ko.exportSymbol('contextFor', ko.contextFor);
7.2171 + ko.exportSymbol('dataFor', ko.dataFor);
7.2172 +})();
7.2173 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
7.2174 +ko.bindingHandlers['attr'] = {
7.2175 + 'update': function(element, valueAccessor, allBindingsAccessor) {
7.2176 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
7.2177 + for (var attrName in value) {
7.2178 + if (typeof attrName == "string") {
7.2179 + var attrValue = ko.utils.unwrapObservable(value[attrName]);
7.2180 +
7.2181 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
7.2182 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
7.2183 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
7.2184 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
7.2185 + if (toRemove)
7.2186 + element.removeAttribute(attrName);
7.2187 +
7.2188 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
7.2189 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
7.2190 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
7.2191 + // property for IE <= 8.
7.2192 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
7.2193 + attrName = attrHtmlToJavascriptMap[attrName];
7.2194 + if (toRemove)
7.2195 + element.removeAttribute(attrName);
7.2196 + else
7.2197 + element[attrName] = attrValue;
7.2198 + } else if (!toRemove) {
7.2199 + try {
7.2200 + element.setAttribute(attrName, attrValue.toString());
7.2201 + } catch (err) {
7.2202 + // ignore for now
7.2203 + if (console) {
7.2204 + console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
7.2205 + }
7.2206 + }
7.2207 + }
7.2208 +
7.2209 + // Treat "name" specially - although you can think of it as an attribute, it also needs
7.2210 + // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
7.2211 + // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
7.2212 + // entirely, and there's no strong reason to allow for such casing in HTML.
7.2213 + if (attrName === "name") {
7.2214 + ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
7.2215 + }
7.2216 + }
7.2217 + }
7.2218 + }
7.2219 +};
7.2220 +ko.bindingHandlers['checked'] = {
7.2221 + 'init': function (element, valueAccessor, allBindingsAccessor) {
7.2222 + var updateHandler = function() {
7.2223 + var valueToWrite;
7.2224 + if (element.type == "checkbox") {
7.2225 + valueToWrite = element.checked;
7.2226 + } else if ((element.type == "radio") && (element.checked)) {
7.2227 + valueToWrite = element.value;
7.2228 + } else {
7.2229 + return; // "checked" binding only responds to checkboxes and selected radio buttons
7.2230 + }
7.2231 +
7.2232 + var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
7.2233 + if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
7.2234 + // For checkboxes bound to an array, we add/remove the checkbox value to that array
7.2235 + // This works for both observable and non-observable arrays
7.2236 + var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
7.2237 + if (element.checked && (existingEntryIndex < 0))
7.2238 + modelValue.push(element.value);
7.2239 + else if ((!element.checked) && (existingEntryIndex >= 0))
7.2240 + modelValue.splice(existingEntryIndex, 1);
7.2241 + } else {
7.2242 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
7.2243 + }
7.2244 + };
7.2245 + ko.utils.registerEventHandler(element, "click", updateHandler);
7.2246 +
7.2247 + // IE 6 won't allow radio buttons to be selected unless they have a name
7.2248 + if ((element.type == "radio") && !element.name)
7.2249 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
7.2250 + },
7.2251 + 'update': function (element, valueAccessor) {
7.2252 + var value = ko.utils.unwrapObservable(valueAccessor());
7.2253 +
7.2254 + if (element.type == "checkbox") {
7.2255 + if (value instanceof Array) {
7.2256 + // When bound to an array, the checkbox being checked represents its value being present in that array
7.2257 + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
7.2258 + } else {
7.2259 + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
7.2260 + element.checked = value;
7.2261 + }
7.2262 + } else if (element.type == "radio") {
7.2263 + element.checked = (element.value == value);
7.2264 + }
7.2265 + }
7.2266 +};
7.2267 +var classesWrittenByBindingKey = '__ko__cssValue';
7.2268 +ko.bindingHandlers['css'] = {
7.2269 + 'update': function (element, valueAccessor) {
7.2270 + var value = ko.utils.unwrapObservable(valueAccessor());
7.2271 + if (typeof value == "object") {
7.2272 + for (var className in value) {
7.2273 + var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
7.2274 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
7.2275 + }
7.2276 + } else {
7.2277 + value = String(value || ''); // Make sure we don't try to store or set a non-string value
7.2278 + ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
7.2279 + element[classesWrittenByBindingKey] = value;
7.2280 + ko.utils.toggleDomNodeCssClass(element, value, true);
7.2281 + }
7.2282 + }
7.2283 +};
7.2284 +ko.bindingHandlers['enable'] = {
7.2285 + 'update': function (element, valueAccessor) {
7.2286 + var value = ko.utils.unwrapObservable(valueAccessor());
7.2287 + if (value && element.disabled)
7.2288 + element.removeAttribute("disabled");
7.2289 + else if ((!value) && (!element.disabled))
7.2290 + element.disabled = true;
7.2291 + }
7.2292 +};
7.2293 +
7.2294 +ko.bindingHandlers['disable'] = {
7.2295 + 'update': function (element, valueAccessor) {
7.2296 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
7.2297 + }
7.2298 +};
7.2299 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
7.2300 +// e.g. click:handler instead of the usual full-length event:{click:handler}
7.2301 +function makeEventHandlerShortcut(eventName) {
7.2302 + ko.bindingHandlers[eventName] = {
7.2303 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
7.2304 + var newValueAccessor = function () {
7.2305 + var result = {};
7.2306 + result[eventName] = valueAccessor();
7.2307 + return result;
7.2308 + };
7.2309 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
7.2310 + }
7.2311 + }
7.2312 +}
7.2313 +
7.2314 +ko.bindingHandlers['event'] = {
7.2315 + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
7.2316 + var eventsToHandle = valueAccessor() || {};
7.2317 + for(var eventNameOutsideClosure in eventsToHandle) {
7.2318 + (function() {
7.2319 + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
7.2320 + if (typeof eventName == "string") {
7.2321 + ko.utils.registerEventHandler(element, eventName, function (event) {
7.2322 + var handlerReturnValue;
7.2323 + var handlerFunction = valueAccessor()[eventName];
7.2324 + if (!handlerFunction)
7.2325 + return;
7.2326 + var allBindings = allBindingsAccessor();
7.2327 +
7.2328 + try {
7.2329 + // Take all the event args, and prefix with the viewmodel
7.2330 + var argsForHandler = ko.utils.makeArray(arguments);
7.2331 + argsForHandler.unshift(viewModel);
7.2332 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
7.2333 + } finally {
7.2334 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
7.2335 + if (event.preventDefault)
7.2336 + event.preventDefault();
7.2337 + else
7.2338 + event.returnValue = false;
7.2339 + }
7.2340 + }
7.2341 +
7.2342 + var bubble = allBindings[eventName + 'Bubble'] !== false;
7.2343 + if (!bubble) {
7.2344 + event.cancelBubble = true;
7.2345 + if (event.stopPropagation)
7.2346 + event.stopPropagation();
7.2347 + }
7.2348 + });
7.2349 + }
7.2350 + })();
7.2351 + }
7.2352 + }
7.2353 +};
7.2354 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
7.2355 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
7.2356 +ko.bindingHandlers['foreach'] = {
7.2357 + makeTemplateValueAccessor: function(valueAccessor) {
7.2358 + return function() {
7.2359 + var modelValue = valueAccessor(),
7.2360 + unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
7.2361 +
7.2362 + // If unwrappedValue is the array, pass in the wrapped value on its own
7.2363 + // The value will be unwrapped and tracked within the template binding
7.2364 + // (See https://github.com/SteveSanderson/knockout/issues/523)
7.2365 + if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
7.2366 + return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
7.2367 +
7.2368 + // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
7.2369 + ko.utils.unwrapObservable(modelValue);
7.2370 + return {
7.2371 + 'foreach': unwrappedValue['data'],
7.2372 + 'as': unwrappedValue['as'],
7.2373 + 'includeDestroyed': unwrappedValue['includeDestroyed'],
7.2374 + 'afterAdd': unwrappedValue['afterAdd'],
7.2375 + 'beforeRemove': unwrappedValue['beforeRemove'],
7.2376 + 'afterRender': unwrappedValue['afterRender'],
7.2377 + 'beforeMove': unwrappedValue['beforeMove'],
7.2378 + 'afterMove': unwrappedValue['afterMove'],
7.2379 + 'templateEngine': ko.nativeTemplateEngine.instance
7.2380 + };
7.2381 + };
7.2382 + },
7.2383 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
7.2384 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
7.2385 + },
7.2386 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
7.2387 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
7.2388 + }
7.2389 +};
7.2390 +ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
7.2391 +ko.virtualElements.allowedBindings['foreach'] = true;
7.2392 +var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
7.2393 +ko.bindingHandlers['hasfocus'] = {
7.2394 + 'init': function(element, valueAccessor, allBindingsAccessor) {
7.2395 + var handleElementFocusChange = function(isFocused) {
7.2396 + // Where possible, ignore which event was raised and determine focus state using activeElement,
7.2397 + // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
7.2398 + // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
7.2399 + // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
7.2400 + // from calling 'blur()' on the element when it loses focus.
7.2401 + // Discussion at https://github.com/SteveSanderson/knockout/pull/352
7.2402 + element[hasfocusUpdatingProperty] = true;
7.2403 + var ownerDoc = element.ownerDocument;
7.2404 + if ("activeElement" in ownerDoc) {
7.2405 + isFocused = (ownerDoc.activeElement === element);
7.2406 + }
7.2407 + var modelValue = valueAccessor();
7.2408 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
7.2409 + element[hasfocusUpdatingProperty] = false;
7.2410 + };
7.2411 + var handleElementFocusIn = handleElementFocusChange.bind(null, true);
7.2412 + var handleElementFocusOut = handleElementFocusChange.bind(null, false);
7.2413 +
7.2414 + ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
7.2415 + ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
7.2416 + ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
7.2417 + ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
7.2418 + },
7.2419 + 'update': function(element, valueAccessor) {
7.2420 + var value = ko.utils.unwrapObservable(valueAccessor());
7.2421 + if (!element[hasfocusUpdatingProperty]) {
7.2422 + value ? element.focus() : element.blur();
7.2423 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
7.2424 + }
7.2425 + }
7.2426 +};
7.2427 +ko.bindingHandlers['html'] = {
7.2428 + 'init': function() {
7.2429 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
7.2430 + return { 'controlsDescendantBindings': true };
7.2431 + },
7.2432 + 'update': function (element, valueAccessor) {
7.2433 + // setHtml will unwrap the value if needed
7.2434 + ko.utils.setHtml(element, valueAccessor());
7.2435 + }
7.2436 +};
7.2437 +var withIfDomDataKey = '__ko_withIfBindingData';
7.2438 +// Makes a binding like with or if
7.2439 +function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
7.2440 + ko.bindingHandlers[bindingKey] = {
7.2441 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
7.2442 + ko.utils.domData.set(element, withIfDomDataKey, {});
7.2443 + return { 'controlsDescendantBindings': true };
7.2444 + },
7.2445 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
7.2446 + var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
7.2447 + dataValue = ko.utils.unwrapObservable(valueAccessor()),
7.2448 + shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
7.2449 + isFirstRender = !withIfData.savedNodes,
7.2450 + needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
7.2451 +
7.2452 + if (needsRefresh) {
7.2453 + if (isFirstRender) {
7.2454 + withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
7.2455 + }
7.2456 +
7.2457 + if (shouldDisplay) {
7.2458 + if (!isFirstRender) {
7.2459 + ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
7.2460 + }
7.2461 + ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
7.2462 + } else {
7.2463 + ko.virtualElements.emptyNode(element);
7.2464 + }
7.2465 +
7.2466 + withIfData.didDisplayOnLastUpdate = shouldDisplay;
7.2467 + }
7.2468 + }
7.2469 + };
7.2470 + ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
7.2471 + ko.virtualElements.allowedBindings[bindingKey] = true;
7.2472 +}
7.2473 +
7.2474 +// Construct the actual binding handlers
7.2475 +makeWithIfBinding('if');
7.2476 +makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
7.2477 +makeWithIfBinding('with', true /* isWith */, false /* isNot */,
7.2478 + function(bindingContext, dataValue) {
7.2479 + return bindingContext['createChildContext'](dataValue);
7.2480 + }
7.2481 +);
7.2482 +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
7.2483 + if (preferModelValue) {
7.2484 + if (modelValue !== ko.selectExtensions.readValue(element))
7.2485 + ko.selectExtensions.writeValue(element, modelValue);
7.2486 + }
7.2487 +
7.2488 + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
7.2489 + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
7.2490 + // change the model value to match the dropdown.
7.2491 + if (modelValue !== ko.selectExtensions.readValue(element))
7.2492 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
7.2493 +};
7.2494 +
7.2495 +ko.bindingHandlers['options'] = {
7.2496 + 'update': function (element, valueAccessor, allBindingsAccessor) {
7.2497 + if (ko.utils.tagNameLower(element) !== "select")
7.2498 + throw new Error("options binding applies only to SELECT elements");
7.2499 +
7.2500 + var selectWasPreviouslyEmpty = element.length == 0;
7.2501 + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
7.2502 + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
7.2503 + }), function (node) {
7.2504 + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
7.2505 + });
7.2506 + var previousScrollTop = element.scrollTop;
7.2507 +
7.2508 + var value = ko.utils.unwrapObservable(valueAccessor());
7.2509 + var selectedValue = element.value;
7.2510 +
7.2511 + // Remove all existing <option>s.
7.2512 + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
7.2513 + while (element.length > 0) {
7.2514 + ko.cleanNode(element.options[0]);
7.2515 + element.remove(0);
7.2516 + }
7.2517 +
7.2518 + if (value) {
7.2519 + var allBindings = allBindingsAccessor(),
7.2520 + includeDestroyed = allBindings['optionsIncludeDestroyed'];
7.2521 +
7.2522 + if (typeof value.length != "number")
7.2523 + value = [value];
7.2524 + if (allBindings['optionsCaption']) {
7.2525 + var option = document.createElement("option");
7.2526 + ko.utils.setHtml(option, allBindings['optionsCaption']);
7.2527 + ko.selectExtensions.writeValue(option, undefined);
7.2528 + element.appendChild(option);
7.2529 + }
7.2530 +
7.2531 + for (var i = 0, j = value.length; i < j; i++) {
7.2532 + // Skip destroyed items
7.2533 + var arrayEntry = value[i];
7.2534 + if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
7.2535 + continue;
7.2536 +
7.2537 + var option = document.createElement("option");
7.2538 +
7.2539 + function applyToObject(object, predicate, defaultValue) {
7.2540 + var predicateType = typeof predicate;
7.2541 + if (predicateType == "function") // Given a function; run it against the data value
7.2542 + return predicate(object);
7.2543 + else if (predicateType == "string") // Given a string; treat it as a property name on the data value
7.2544 + return object[predicate];
7.2545 + else // Given no optionsText arg; use the data value itself
7.2546 + return defaultValue;
7.2547 + }
7.2548 +
7.2549 + // Apply a value to the option element
7.2550 + var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
7.2551 + ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
7.2552 +
7.2553 + // Apply some text to the option element
7.2554 + var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
7.2555 + ko.utils.setTextContent(option, optionText);
7.2556 +
7.2557 + element.appendChild(option);
7.2558 + }
7.2559 +
7.2560 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
7.2561 + // That's why we first added them without selection. Now it's time to set the selection.
7.2562 + var newOptions = element.getElementsByTagName("option");
7.2563 + var countSelectionsRetained = 0;
7.2564 + for (var i = 0, j = newOptions.length; i < j; i++) {
7.2565 + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
7.2566 + ko.utils.setOptionNodeSelectionState(newOptions[i], true);
7.2567 + countSelectionsRetained++;
7.2568 + }
7.2569 + }
7.2570 +
7.2571 + element.scrollTop = previousScrollTop;
7.2572 +
7.2573 + if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
7.2574 + // Ensure consistency between model value and selected option.
7.2575 + // If the dropdown is being populated for the first time here (or was otherwise previously empty),
7.2576 + // the dropdown selection state is meaningless, so we preserve the model value.
7.2577 + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
7.2578 + }
7.2579 +
7.2580 + // Workaround for IE9 bug
7.2581 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
7.2582 + }
7.2583 + }
7.2584 +};
7.2585 +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
7.2586 +ko.bindingHandlers['selectedOptions'] = {
7.2587 + 'init': function (element, valueAccessor, allBindingsAccessor) {
7.2588 + ko.utils.registerEventHandler(element, "change", function () {
7.2589 + var value = valueAccessor(), valueToWrite = [];
7.2590 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
7.2591 + if (node.selected)
7.2592 + valueToWrite.push(ko.selectExtensions.readValue(node));
7.2593 + });
7.2594 + ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
7.2595 + });
7.2596 + },
7.2597 + 'update': function (element, valueAccessor) {
7.2598 + if (ko.utils.tagNameLower(element) != "select")
7.2599 + throw new Error("values binding applies only to SELECT elements");
7.2600 +
7.2601 + var newValue = ko.utils.unwrapObservable(valueAccessor());
7.2602 + if (newValue && typeof newValue.length == "number") {
7.2603 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
7.2604 + var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
7.2605 + ko.utils.setOptionNodeSelectionState(node, isSelected);
7.2606 + });
7.2607 + }
7.2608 + }
7.2609 +};
7.2610 +ko.bindingHandlers['style'] = {
7.2611 + 'update': function (element, valueAccessor) {
7.2612 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
7.2613 + for (var styleName in value) {
7.2614 + if (typeof styleName == "string") {
7.2615 + var styleValue = ko.utils.unwrapObservable(value[styleName]);
7.2616 + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
7.2617 + }
7.2618 + }
7.2619 + }
7.2620 +};
7.2621 +ko.bindingHandlers['submit'] = {
7.2622 + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
7.2623 + if (typeof valueAccessor() != "function")
7.2624 + throw new Error("The value for a submit binding must be a function");
7.2625 + ko.utils.registerEventHandler(element, "submit", function (event) {
7.2626 + var handlerReturnValue;
7.2627 + var value = valueAccessor();
7.2628 + try { handlerReturnValue = value.call(viewModel, element); }
7.2629 + finally {
7.2630 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
7.2631 + if (event.preventDefault)
7.2632 + event.preventDefault();
7.2633 + else
7.2634 + event.returnValue = false;
7.2635 + }
7.2636 + }
7.2637 + });
7.2638 + }
7.2639 +};
7.2640 +ko.bindingHandlers['text'] = {
7.2641 + 'update': function (element, valueAccessor) {
7.2642 + ko.utils.setTextContent(element, valueAccessor());
7.2643 + }
7.2644 +};
7.2645 +ko.virtualElements.allowedBindings['text'] = true;
7.2646 +ko.bindingHandlers['uniqueName'] = {
7.2647 + 'init': function (element, valueAccessor) {
7.2648 + if (valueAccessor()) {
7.2649 + var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
7.2650 + ko.utils.setElementName(element, name);
7.2651 + }
7.2652 + }
7.2653 +};
7.2654 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
7.2655 +ko.bindingHandlers['value'] = {
7.2656 + 'init': function (element, valueAccessor, allBindingsAccessor) {
7.2657 + // Always catch "change" event; possibly other events too if asked
7.2658 + var eventsToCatch = ["change"];
7.2659 + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
7.2660 + var propertyChangedFired = false;
7.2661 + if (requestedEventsToCatch) {
7.2662 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
7.2663 + requestedEventsToCatch = [requestedEventsToCatch];
7.2664 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
7.2665 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
7.2666 + }
7.2667 +
7.2668 + var valueUpdateHandler = function() {
7.2669 + propertyChangedFired = false;
7.2670 + var modelValue = valueAccessor();
7.2671 + var elementValue = ko.selectExtensions.readValue(element);
7.2672 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
7.2673 + }
7.2674 +
7.2675 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
7.2676 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
7.2677 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
7.2678 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
7.2679 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
7.2680 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
7.2681 + ko.utils.registerEventHandler(element, "blur", function() {
7.2682 + if (propertyChangedFired) {
7.2683 + valueUpdateHandler();
7.2684 + }
7.2685 + });
7.2686 + }
7.2687 +
7.2688 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
7.2689 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
7.2690 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
7.2691 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
7.2692 + var handler = valueUpdateHandler;
7.2693 + if (ko.utils.stringStartsWith(eventName, "after")) {
7.2694 + handler = function() { setTimeout(valueUpdateHandler, 0) };
7.2695 + eventName = eventName.substring("after".length);
7.2696 + }
7.2697 + ko.utils.registerEventHandler(element, eventName, handler);
7.2698 + });
7.2699 + },
7.2700 + 'update': function (element, valueAccessor) {
7.2701 + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
7.2702 + var newValue = ko.utils.unwrapObservable(valueAccessor());
7.2703 + var elementValue = ko.selectExtensions.readValue(element);
7.2704 + var valueHasChanged = (newValue != elementValue);
7.2705 +
7.2706 + // 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).
7.2707 + // 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.
7.2708 + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
7.2709 + valueHasChanged = true;
7.2710 +
7.2711 + if (valueHasChanged) {
7.2712 + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
7.2713 + applyValueAction();
7.2714 +
7.2715 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
7.2716 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
7.2717 + // to apply the value as well.
7.2718 + var alsoApplyAsynchronously = valueIsSelectOption;
7.2719 + if (alsoApplyAsynchronously)
7.2720 + setTimeout(applyValueAction, 0);
7.2721 + }
7.2722 +
7.2723 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
7.2724 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
7.2725 + if (valueIsSelectOption && (element.length > 0))
7.2726 + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
7.2727 + }
7.2728 +};
7.2729 +ko.bindingHandlers['visible'] = {
7.2730 + 'update': function (element, valueAccessor) {
7.2731 + var value = ko.utils.unwrapObservable(valueAccessor());
7.2732 + var isCurrentlyVisible = !(element.style.display == "none");
7.2733 + if (value && !isCurrentlyVisible)
7.2734 + element.style.display = "";
7.2735 + else if ((!value) && isCurrentlyVisible)
7.2736 + element.style.display = "none";
7.2737 + }
7.2738 +};
7.2739 +// 'click' is just a shorthand for the usual full-length event:{click:handler}
7.2740 +makeEventHandlerShortcut('click');
7.2741 +// If you want to make a custom template engine,
7.2742 +//
7.2743 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
7.2744 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
7.2745 +//
7.2746 +// function (templateSource, bindingContext, options) {
7.2747 +// // - templateSource.text() is the text of the template you should render
7.2748 +// // - bindingContext.$data is the data you should pass into the template
7.2749 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
7.2750 +// // and bindingContext.$root available in the template too
7.2751 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
7.2752 +// //
7.2753 +// // Return value: an array of DOM nodes
7.2754 +// }
7.2755 +//
7.2756 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
7.2757 +//
7.2758 +// function (script) {
7.2759 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
7.2760 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
7.2761 +// }
7.2762 +//
7.2763 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
7.2764 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
7.2765 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
7.2766 +
7.2767 +ko.templateEngine = function () { };
7.2768 +
7.2769 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
7.2770 + throw new Error("Override renderTemplateSource");
7.2771 +};
7.2772 +
7.2773 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
7.2774 + throw new Error("Override createJavaScriptEvaluatorBlock");
7.2775 +};
7.2776 +
7.2777 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
7.2778 + // Named template
7.2779 + if (typeof template == "string") {
7.2780 + templateDocument = templateDocument || document;
7.2781 + var elem = templateDocument.getElementById(template);
7.2782 + if (!elem)
7.2783 + throw new Error("Cannot find template with ID " + template);
7.2784 + return new ko.templateSources.domElement(elem);
7.2785 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
7.2786 + // Anonymous template
7.2787 + return new ko.templateSources.anonymousTemplate(template);
7.2788 + } else
7.2789 + throw new Error("Unknown template type: " + template);
7.2790 +};
7.2791 +
7.2792 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
7.2793 + var templateSource = this['makeTemplateSource'](template, templateDocument);
7.2794 + return this['renderTemplateSource'](templateSource, bindingContext, options);
7.2795 +};
7.2796 +
7.2797 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
7.2798 + // Skip rewriting if requested
7.2799 + if (this['allowTemplateRewriting'] === false)
7.2800 + return true;
7.2801 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
7.2802 +};
7.2803 +
7.2804 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
7.2805 + var templateSource = this['makeTemplateSource'](template, templateDocument);
7.2806 + var rewritten = rewriterCallback(templateSource['text']());
7.2807 + templateSource['text'](rewritten);
7.2808 + templateSource['data']("isRewritten", true);
7.2809 +};
7.2810 +
7.2811 +ko.exportSymbol('templateEngine', ko.templateEngine);
7.2812 +
7.2813 +ko.templateRewriting = (function () {
7.2814 + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
7.2815 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
7.2816 +
7.2817 + function validateDataBindValuesForRewriting(keyValueArray) {
7.2818 + var allValidators = ko.expressionRewriting.bindingRewriteValidators;
7.2819 + for (var i = 0; i < keyValueArray.length; i++) {
7.2820 + var key = keyValueArray[i]['key'];
7.2821 + if (allValidators.hasOwnProperty(key)) {
7.2822 + var validator = allValidators[key];
7.2823 +
7.2824 + if (typeof validator === "function") {
7.2825 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
7.2826 + if (possibleErrorMessage)
7.2827 + throw new Error(possibleErrorMessage);
7.2828 + } else if (!validator) {
7.2829 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
7.2830 + }
7.2831 + }
7.2832 + }
7.2833 + }
7.2834 +
7.2835 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
7.2836 + var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
7.2837 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
7.2838 + var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
7.2839 +
7.2840 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
7.2841 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
7.2842 + // extra indirection.
7.2843 + var applyBindingsToNextSiblingScript =
7.2844 + "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
7.2845 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
7.2846 + }
7.2847 +
7.2848 + return {
7.2849 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
7.2850 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
7.2851 + templateEngine['rewriteTemplate'](template, function (htmlString) {
7.2852 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
7.2853 + }, templateDocument);
7.2854 + },
7.2855 +
7.2856 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
7.2857 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
7.2858 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
7.2859 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
7.2860 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
7.2861 + });
7.2862 + },
7.2863 +
7.2864 + applyMemoizedBindingsToNextSibling: function (bindings) {
7.2865 + return ko.memoization.memoize(function (domNode, bindingContext) {
7.2866 + if (domNode.nextSibling)
7.2867 + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
7.2868 + });
7.2869 + }
7.2870 + }
7.2871 +})();
7.2872 +
7.2873 +
7.2874 +// Exported only because it has to be referenced by string lookup from within rewritten template
7.2875 +ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
7.2876 +(function() {
7.2877 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
7.2878 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
7.2879 + //
7.2880 + // Two are provided by default:
7.2881 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
7.2882 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
7.2883 + // without reading/writing the actual element text content, since it will be overwritten
7.2884 + // with the rendered template output.
7.2885 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
7.2886 + // Template sources need to have the following functions:
7.2887 + // text() - returns the template text from your storage location
7.2888 + // text(value) - writes the supplied template text to your storage location
7.2889 + // data(key) - reads values stored using data(key, value) - see below
7.2890 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
7.2891 + //
7.2892 + // Optionally, template sources can also have the following functions:
7.2893 + // nodes() - returns a DOM element containing the nodes of this template, where available
7.2894 + // nodes(value) - writes the given DOM element to your storage location
7.2895 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
7.2896 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
7.2897 + //
7.2898 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
7.2899 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
7.2900 +
7.2901 + ko.templateSources = {};
7.2902 +
7.2903 + // ---- ko.templateSources.domElement -----
7.2904 +
7.2905 + ko.templateSources.domElement = function(element) {
7.2906 + this.domElement = element;
7.2907 + }
7.2908 +
7.2909 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
7.2910 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
7.2911 + elemContentsProperty = tagNameLower === "script" ? "text"
7.2912 + : tagNameLower === "textarea" ? "value"
7.2913 + : "innerHTML";
7.2914 +
7.2915 + if (arguments.length == 0) {
7.2916 + return this.domElement[elemContentsProperty];
7.2917 + } else {
7.2918 + var valueToWrite = arguments[0];
7.2919 + if (elemContentsProperty === "innerHTML")
7.2920 + ko.utils.setHtml(this.domElement, valueToWrite);
7.2921 + else
7.2922 + this.domElement[elemContentsProperty] = valueToWrite;
7.2923 + }
7.2924 + };
7.2925 +
7.2926 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
7.2927 + if (arguments.length === 1) {
7.2928 + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
7.2929 + } else {
7.2930 + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
7.2931 + }
7.2932 + };
7.2933 +
7.2934 + // ---- ko.templateSources.anonymousTemplate -----
7.2935 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
7.2936 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
7.2937 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
7.2938 +
7.2939 + var anonymousTemplatesDomDataKey = "__ko_anon_template__";
7.2940 + ko.templateSources.anonymousTemplate = function(element) {
7.2941 + this.domElement = element;
7.2942 + }
7.2943 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
7.2944 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
7.2945 + if (arguments.length == 0) {
7.2946 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
7.2947 + if (templateData.textData === undefined && templateData.containerData)
7.2948 + templateData.textData = templateData.containerData.innerHTML;
7.2949 + return templateData.textData;
7.2950 + } else {
7.2951 + var valueToWrite = arguments[0];
7.2952 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
7.2953 + }
7.2954 + };
7.2955 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
7.2956 + if (arguments.length == 0) {
7.2957 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
7.2958 + return templateData.containerData;
7.2959 + } else {
7.2960 + var valueToWrite = arguments[0];
7.2961 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
7.2962 + }
7.2963 + };
7.2964 +
7.2965 + ko.exportSymbol('templateSources', ko.templateSources);
7.2966 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
7.2967 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
7.2968 +})();
7.2969 +(function () {
7.2970 + var _templateEngine;
7.2971 + ko.setTemplateEngine = function (templateEngine) {
7.2972 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
7.2973 + throw new Error("templateEngine must inherit from ko.templateEngine");
7.2974 + _templateEngine = templateEngine;
7.2975 + }
7.2976 +
7.2977 + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
7.2978 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
7.2979 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
7.2980 + nextInQueue = ko.virtualElements.nextSibling(node);
7.2981 + if (node.nodeType === 1 || node.nodeType === 8)
7.2982 + action(node);
7.2983 + }
7.2984 + }
7.2985 +
7.2986 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
7.2987 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
7.2988 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
7.2989 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
7.2990 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
7.2991 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
7.2992 +
7.2993 + if (continuousNodeArray.length) {
7.2994 + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
7.2995 +
7.2996 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
7.2997 + // whereas a regular applyBindings won't introduce new memoized nodes
7.2998 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
7.2999 + ko.applyBindings(bindingContext, node);
7.3000 + });
7.3001 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
7.3002 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
7.3003 + });
7.3004 + }
7.3005 + }
7.3006 +
7.3007 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
7.3008 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
7.3009 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
7.3010 + : null;
7.3011 + }
7.3012 +
7.3013 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
7.3014 + options = options || {};
7.3015 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
7.3016 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
7.3017 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
7.3018 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
7.3019 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
7.3020 +
7.3021 + // Loosely check result is an array of DOM nodes
7.3022 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
7.3023 + throw new Error("Template engine must return an array of DOM nodes");
7.3024 +
7.3025 + var haveAddedNodesToParent = false;
7.3026 + switch (renderMode) {
7.3027 + case "replaceChildren":
7.3028 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
7.3029 + haveAddedNodesToParent = true;
7.3030 + break;
7.3031 + case "replaceNode":
7.3032 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
7.3033 + haveAddedNodesToParent = true;
7.3034 + break;
7.3035 + case "ignoreTargetNode": break;
7.3036 + default:
7.3037 + throw new Error("Unknown renderMode: " + renderMode);
7.3038 + }
7.3039 +
7.3040 + if (haveAddedNodesToParent) {
7.3041 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
7.3042 + if (options['afterRender'])
7.3043 + ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
7.3044 + }
7.3045 +
7.3046 + return renderedNodesArray;
7.3047 + }
7.3048 +
7.3049 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
7.3050 + options = options || {};
7.3051 + if ((options['templateEngine'] || _templateEngine) == undefined)
7.3052 + throw new Error("Set a template engine before calling renderTemplate");
7.3053 + renderMode = renderMode || "replaceChildren";
7.3054 +
7.3055 + if (targetNodeOrNodeArray) {
7.3056 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
7.3057 +
7.3058 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
7.3059 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
7.3060 +
7.3061 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
7.3062 + function () {
7.3063 + // Ensure we've got a proper binding context to work with
7.3064 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
7.3065 + ? dataOrBindingContext
7.3066 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
7.3067 +
7.3068 + // Support selecting template as a function of the data being rendered
7.3069 + var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
7.3070 +
7.3071 + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
7.3072 + if (renderMode == "replaceNode") {
7.3073 + targetNodeOrNodeArray = renderedNodesArray;
7.3074 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
7.3075 + }
7.3076 + },
7.3077 + null,
7.3078 + { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
7.3079 + );
7.3080 + } else {
7.3081 + // 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
7.3082 + return ko.memoization.memoize(function (domNode) {
7.3083 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
7.3084 + });
7.3085 + }
7.3086 + };
7.3087 +
7.3088 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
7.3089 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
7.3090 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
7.3091 + var arrayItemContext;
7.3092 +
7.3093 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
7.3094 + var executeTemplateForArrayItem = function (arrayValue, index) {
7.3095 + // Support selecting template as a function of the data being rendered
7.3096 + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
7.3097 + arrayItemContext['$index'] = index;
7.3098 + var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
7.3099 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
7.3100 + }
7.3101 +
7.3102 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
7.3103 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
7.3104 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
7.3105 + if (options['afterRender'])
7.3106 + options['afterRender'](addedNodesArray, arrayValue);
7.3107 + };
7.3108 +
7.3109 + return ko.dependentObservable(function () {
7.3110 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
7.3111 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
7.3112 + unwrappedArray = [unwrappedArray];
7.3113 +
7.3114 + // Filter out any entries marked as destroyed
7.3115 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
7.3116 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
7.3117 + });
7.3118 +
7.3119 + // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
7.3120 + // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
7.3121 + ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
7.3122 +
7.3123 + }, null, { disposeWhenNodeIsRemoved: targetNode });
7.3124 + };
7.3125 +
7.3126 + var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
7.3127 + function disposeOldComputedAndStoreNewOne(element, newComputed) {
7.3128 + var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
7.3129 + if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
7.3130 + oldComputed.dispose();
7.3131 + ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
7.3132 + }
7.3133 +
7.3134 + ko.bindingHandlers['template'] = {
7.3135 + 'init': function(element, valueAccessor) {
7.3136 + // Support anonymous templates
7.3137 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
7.3138 + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
7.3139 + // It's an anonymous template - store the element contents, then clear the element
7.3140 + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
7.3141 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
7.3142 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
7.3143 + }
7.3144 + return { 'controlsDescendantBindings': true };
7.3145 + },
7.3146 + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
7.3147 + var templateName = ko.utils.unwrapObservable(valueAccessor()),
7.3148 + options = {},
7.3149 + shouldDisplay = true,
7.3150 + dataValue,
7.3151 + templateComputed = null;
7.3152 +
7.3153 + if (typeof templateName != "string") {
7.3154 + options = templateName;
7.3155 + templateName = options['name'];
7.3156 +
7.3157 + // Support "if"/"ifnot" conditions
7.3158 + if ('if' in options)
7.3159 + shouldDisplay = ko.utils.unwrapObservable(options['if']);
7.3160 + if (shouldDisplay && 'ifnot' in options)
7.3161 + shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
7.3162 +
7.3163 + dataValue = ko.utils.unwrapObservable(options['data']);
7.3164 + }
7.3165 +
7.3166 + if ('foreach' in options) {
7.3167 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
7.3168 + var dataArray = (shouldDisplay && options['foreach']) || [];
7.3169 + templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
7.3170 + } else if (!shouldDisplay) {
7.3171 + ko.virtualElements.emptyNode(element);
7.3172 + } else {
7.3173 + // Render once for this single data point (or use the viewModel if no data was provided)
7.3174 + var innerBindingContext = ('data' in options) ?
7.3175 + bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
7.3176 + bindingContext; // Given no explicit 'data' value, we retain the same binding context
7.3177 + templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
7.3178 + }
7.3179 +
7.3180 + // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
7.3181 + disposeOldComputedAndStoreNewOne(element, templateComputed);
7.3182 + }
7.3183 + };
7.3184 +
7.3185 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
7.3186 + ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
7.3187 + var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
7.3188 +
7.3189 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
7.3190 + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
7.3191 +
7.3192 + if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
7.3193 + return null; // Named templates can be rewritten, so return "no error"
7.3194 + return "This template engine does not support anonymous templates nested within its templates";
7.3195 + };
7.3196 +
7.3197 + ko.virtualElements.allowedBindings['template'] = true;
7.3198 +})();
7.3199 +
7.3200 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
7.3201 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
7.3202 +
7.3203 +ko.utils.compareArrays = (function () {
7.3204 + var statusNotInOld = 'added', statusNotInNew = 'deleted';
7.3205 +
7.3206 + // Simple calculation based on Levenshtein distance.
7.3207 + function compareArrays(oldArray, newArray, dontLimitMoves) {
7.3208 + oldArray = oldArray || [];
7.3209 + newArray = newArray || [];
7.3210 +
7.3211 + if (oldArray.length <= newArray.length)
7.3212 + return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
7.3213 + else
7.3214 + return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
7.3215 + }
7.3216 +
7.3217 + function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
7.3218 + var myMin = Math.min,
7.3219 + myMax = Math.max,
7.3220 + editDistanceMatrix = [],
7.3221 + smlIndex, smlIndexMax = smlArray.length,
7.3222 + bigIndex, bigIndexMax = bigArray.length,
7.3223 + compareRange = (bigIndexMax - smlIndexMax) || 1,
7.3224 + maxDistance = smlIndexMax + bigIndexMax + 1,
7.3225 + thisRow, lastRow,
7.3226 + bigIndexMaxForRow, bigIndexMinForRow;
7.3227 +
7.3228 + for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
7.3229 + lastRow = thisRow;
7.3230 + editDistanceMatrix.push(thisRow = []);
7.3231 + bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
7.3232 + bigIndexMinForRow = myMax(0, smlIndex - 1);
7.3233 + for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
7.3234 + if (!bigIndex)
7.3235 + thisRow[bigIndex] = smlIndex + 1;
7.3236 + else if (!smlIndex) // Top row - transform empty array into new array via additions
7.3237 + thisRow[bigIndex] = bigIndex + 1;
7.3238 + else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
7.3239 + thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
7.3240 + else {
7.3241 + var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
7.3242 + var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
7.3243 + thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
7.3244 + }
7.3245 + }
7.3246 + }
7.3247 +
7.3248 + var editScript = [], meMinusOne, notInSml = [], notInBig = [];
7.3249 + for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
7.3250 + meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
7.3251 + if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
7.3252 + notInSml.push(editScript[editScript.length] = { // added
7.3253 + 'status': statusNotInSml,
7.3254 + 'value': bigArray[--bigIndex],
7.3255 + 'index': bigIndex });
7.3256 + } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
7.3257 + notInBig.push(editScript[editScript.length] = { // deleted
7.3258 + 'status': statusNotInBig,
7.3259 + 'value': smlArray[--smlIndex],
7.3260 + 'index': smlIndex });
7.3261 + } else {
7.3262 + editScript.push({
7.3263 + 'status': "retained",
7.3264 + 'value': bigArray[--bigIndex] });
7.3265 + --smlIndex;
7.3266 + }
7.3267 + }
7.3268 +
7.3269 + if (notInSml.length && notInBig.length) {
7.3270 + // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
7.3271 + // smlIndexMax keeps the time complexity of this algorithm linear.
7.3272 + var limitFailedCompares = smlIndexMax * 10, failedCompares,
7.3273 + a, d, notInSmlItem, notInBigItem;
7.3274 + // Go through the items that have been added and deleted and try to find matches between them.
7.3275 + for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
7.3276 + for (d = 0; notInBigItem = notInBig[d]; d++) {
7.3277 + if (notInSmlItem['value'] === notInBigItem['value']) {
7.3278 + notInSmlItem['moved'] = notInBigItem['index'];
7.3279 + notInBigItem['moved'] = notInSmlItem['index'];
7.3280 + notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
7.3281 + failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
7.3282 + break;
7.3283 + }
7.3284 + }
7.3285 + failedCompares += d;
7.3286 + }
7.3287 + }
7.3288 + return editScript.reverse();
7.3289 + }
7.3290 +
7.3291 + return compareArrays;
7.3292 +})();
7.3293 +
7.3294 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
7.3295 +
7.3296 +(function () {
7.3297 + // Objective:
7.3298 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
7.3299 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
7.3300 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
7.3301 + // 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
7.3302 + // previously mapped - retain those nodes, and just insert/delete other ones
7.3303 +
7.3304 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
7.3305 + // You can use this, for example, to activate bindings on those nodes.
7.3306 +
7.3307 + function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
7.3308 + // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
7.3309 + // them against what is in the DOM right now. It may be that some of the nodes have already been removed from the document,
7.3310 + // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
7.3311 + // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
7.3312 + // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
7.3313 + //
7.3314 + // Rules:
7.3315 + // [A] Any leading nodes that aren't in the document any more should be ignored
7.3316 + // These most likely correspond to memoization nodes that were already removed during binding
7.3317 + // See https://github.com/SteveSanderson/knockout/pull/440
7.3318 + // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
7.3319 + // have already been removed, and include any nodes that have been inserted among the previous collection
7.3320 +
7.3321 + // Rule [A]
7.3322 + while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
7.3323 + contiguousNodeArray.splice(0, 1);
7.3324 +
7.3325 + // Rule [B]
7.3326 + if (contiguousNodeArray.length > 1) {
7.3327 + // Build up the actual new contiguous node set
7.3328 + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
7.3329 + while (current !== last) {
7.3330 + current = current.nextSibling;
7.3331 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
7.3332 + return;
7.3333 + newContiguousSet.push(current);
7.3334 + }
7.3335 +
7.3336 + // ... then mutate the input array to match this.
7.3337 + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
7.3338 + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
7.3339 + }
7.3340 + return contiguousNodeArray;
7.3341 + }
7.3342 +
7.3343 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
7.3344 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
7.3345 + var mappedNodes = [];
7.3346 + var dependentObservable = ko.dependentObservable(function() {
7.3347 + var newMappedNodes = mapping(valueToMap, index) || [];
7.3348 +
7.3349 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
7.3350 + if (mappedNodes.length > 0) {
7.3351 + ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
7.3352 + if (callbackAfterAddingNodes)
7.3353 + ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
7.3354 + }
7.3355 +
7.3356 + // Replace the contents of the mappedNodes array, thereby updating the record
7.3357 + // of which nodes would be deleted if valueToMap was itself later removed
7.3358 + mappedNodes.splice(0, mappedNodes.length);
7.3359 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
7.3360 + }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
7.3361 + return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
7.3362 + }
7.3363 +
7.3364 + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
7.3365 +
7.3366 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
7.3367 + // Compare the provided array against the previous one
7.3368 + array = array || [];
7.3369 + options = options || {};
7.3370 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
7.3371 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
7.3372 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
7.3373 + var editScript = ko.utils.compareArrays(lastArray, array);
7.3374 +
7.3375 + // Build the new mapping result
7.3376 + var newMappingResult = [];
7.3377 + var lastMappingResultIndex = 0;
7.3378 + var newMappingResultIndex = 0;
7.3379 +
7.3380 + var nodesToDelete = [];
7.3381 + var itemsToProcess = [];
7.3382 + var itemsForBeforeRemoveCallbacks = [];
7.3383 + var itemsForMoveCallbacks = [];
7.3384 + var itemsForAfterAddCallbacks = [];
7.3385 + var mapData;
7.3386 +
7.3387 + function itemMovedOrRetained(editScriptIndex, oldPosition) {
7.3388 + mapData = lastMappingResult[oldPosition];
7.3389 + if (newMappingResultIndex !== oldPosition)
7.3390 + itemsForMoveCallbacks[editScriptIndex] = mapData;
7.3391 + // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
7.3392 + mapData.indexObservable(newMappingResultIndex++);
7.3393 + fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
7.3394 + newMappingResult.push(mapData);
7.3395 + itemsToProcess.push(mapData);
7.3396 + }
7.3397 +
7.3398 + function callCallback(callback, items) {
7.3399 + if (callback) {
7.3400 + for (var i = 0, n = items.length; i < n; i++) {
7.3401 + if (items[i]) {
7.3402 + ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
7.3403 + callback(node, i, items[i].arrayEntry);
7.3404 + });
7.3405 + }
7.3406 + }
7.3407 + }
7.3408 + }
7.3409 +
7.3410 + for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
7.3411 + movedIndex = editScriptItem['moved'];
7.3412 + switch (editScriptItem['status']) {
7.3413 + case "deleted":
7.3414 + if (movedIndex === undefined) {
7.3415 + mapData = lastMappingResult[lastMappingResultIndex];
7.3416 +
7.3417 + // Stop tracking changes to the mapping for these nodes
7.3418 + if (mapData.dependentObservable)
7.3419 + mapData.dependentObservable.dispose();
7.3420 +
7.3421 + // Queue these nodes for later removal
7.3422 + nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
7.3423 + if (options['beforeRemove']) {
7.3424 + itemsForBeforeRemoveCallbacks[i] = mapData;
7.3425 + itemsToProcess.push(mapData);
7.3426 + }
7.3427 + }
7.3428 + lastMappingResultIndex++;
7.3429 + break;
7.3430 +
7.3431 + case "retained":
7.3432 + itemMovedOrRetained(i, lastMappingResultIndex++);
7.3433 + break;
7.3434 +
7.3435 + case "added":
7.3436 + if (movedIndex !== undefined) {
7.3437 + itemMovedOrRetained(i, movedIndex);
7.3438 + } else {
7.3439 + mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
7.3440 + newMappingResult.push(mapData);
7.3441 + itemsToProcess.push(mapData);
7.3442 + if (!isFirstExecution)
7.3443 + itemsForAfterAddCallbacks[i] = mapData;
7.3444 + }
7.3445 + break;
7.3446 + }
7.3447 + }
7.3448 +
7.3449 + // Call beforeMove first before any changes have been made to the DOM
7.3450 + callCallback(options['beforeMove'], itemsForMoveCallbacks);
7.3451 +
7.3452 + // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
7.3453 + ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
7.3454 +
7.3455 + // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
7.3456 + for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
7.3457 + // Get nodes for newly added items
7.3458 + if (!mapData.mappedNodes)
7.3459 + ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
7.3460 +
7.3461 + // Put nodes in the right place if they aren't there already
7.3462 + for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
7.3463 + if (node !== nextNode)
7.3464 + ko.virtualElements.insertAfter(domNode, node, lastNode);
7.3465 + }
7.3466 +
7.3467 + // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
7.3468 + if (!mapData.initialized && callbackAfterAddingNodes) {
7.3469 + callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
7.3470 + mapData.initialized = true;
7.3471 + }
7.3472 + }
7.3473 +
7.3474 + // If there's a beforeRemove callback, call it after reordering.
7.3475 + // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
7.3476 + // some sort of animation, which is why we first reorder the nodes that will be removed. If the
7.3477 + // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
7.3478 + // Perhaps we'll make that change in the future if this scenario becomes more common.
7.3479 + callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
7.3480 +
7.3481 + // Finally call afterMove and afterAdd callbacks
7.3482 + callCallback(options['afterMove'], itemsForMoveCallbacks);
7.3483 + callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
7.3484 +
7.3485 + // Store a copy of the array items we just considered so we can difference it next time
7.3486 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
7.3487 + }
7.3488 +})();
7.3489 +
7.3490 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
7.3491 +ko.nativeTemplateEngine = function () {
7.3492 + this['allowTemplateRewriting'] = false;
7.3493 +}
7.3494 +
7.3495 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
7.3496 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
7.3497 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
7.3498 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
7.3499 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
7.3500 +
7.3501 + if (templateNodes) {
7.3502 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
7.3503 + } else {
7.3504 + var templateText = templateSource['text']();
7.3505 + return ko.utils.parseHtmlFragment(templateText);
7.3506 + }
7.3507 +};
7.3508 +
7.3509 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
7.3510 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
7.3511 +
7.3512 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
7.3513 +(function() {
7.3514 + ko.jqueryTmplTemplateEngine = function () {
7.3515 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
7.3516 + // doesn't expose a version number, so we have to infer it.
7.3517 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
7.3518 + // which KO internally refers to as version "2", so older versions are no longer detected.
7.3519 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
7.3520 + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
7.3521 + return 0;
7.3522 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
7.3523 + try {
7.3524 + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
7.3525 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
7.3526 + return 2; // Final version of jquery.tmpl
7.3527 + }
7.3528 + } catch(ex) { /* Apparently not the version we were looking for */ }
7.3529 +
7.3530 + return 1; // Any older version that we don't support
7.3531 + })();
7.3532 +
7.3533 + function ensureHasReferencedJQueryTemplates() {
7.3534 + if (jQueryTmplVersion < 2)
7.3535 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
7.3536 + }
7.3537 +
7.3538 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
7.3539 + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
7.3540 + }
7.3541 +
7.3542 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
7.3543 + options = options || {};
7.3544 + ensureHasReferencedJQueryTemplates();
7.3545 +
7.3546 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
7.3547 + var precompiled = templateSource['data']('precompiled');
7.3548 + if (!precompiled) {
7.3549 + var templateText = templateSource['text']() || "";
7.3550 + // Wrap in "with($whatever.koBindingContext) { ... }"
7.3551 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
7.3552 +
7.3553 + precompiled = jQuery['template'](null, templateText);
7.3554 + templateSource['data']('precompiled', precompiled);
7.3555 + }
7.3556 +
7.3557 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
7.3558 + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
7.3559 +
7.3560 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
7.3561 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
7.3562 +
7.3563 + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
7.3564 + return resultNodes;
7.3565 + };
7.3566 +
7.3567 + this['createJavaScriptEvaluatorBlock'] = function(script) {
7.3568 + return "{{ko_code ((function() { return " + script + " })()) }}";
7.3569 + };
7.3570 +
7.3571 + this['addTemplate'] = function(templateName, templateMarkup) {
7.3572 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
7.3573 + };
7.3574 +
7.3575 + if (jQueryTmplVersion > 0) {
7.3576 + jQuery['tmpl']['tag']['ko_code'] = {
7.3577 + open: "__.push($1 || '');"
7.3578 + };
7.3579 + jQuery['tmpl']['tag']['ko_with'] = {
7.3580 + open: "with($1) {",
7.3581 + close: "} "
7.3582 + };
7.3583 + }
7.3584 + };
7.3585 +
7.3586 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
7.3587 +
7.3588 + // Use this one by default *only if jquery.tmpl is referenced*
7.3589 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
7.3590 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
7.3591 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
7.3592 +
7.3593 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
7.3594 +})();
7.3595 +});
7.3596 +})(window,document,navigator,window["jQuery"]);
7.3597 +})();
7.3598 \ No newline at end of file
8.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
8.2 +++ b/ko/fx/src/test/java/org/apidesign/bck2brwsr/kofx/KnockoutFXTest.java Wed Jun 26 19:57:38 2013 +0200
8.3 @@ -0,0 +1,123 @@
8.4 +/**
8.5 + * Back 2 Browser Bytecode Translator
8.6 + * Copyright (C) 2012 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.
8.16 + *
8.17 + * You should have received a copy of the GNU General Public License
8.18 + * along with this program. Look for COPYING file in the top folder.
8.19 + * If not, see http://opensource.org/licenses/GPL-2.0.
8.20 + */
8.21 +package org.apidesign.bck2brwsr.kofx;
8.22 +
8.23 +import org.apidesign.bck2brwsr.kofx.FXContext;
8.24 +import java.io.BufferedReader;
8.25 +import java.io.IOException;
8.26 +import java.io.InputStreamReader;
8.27 +import java.io.PrintWriter;
8.28 +import java.net.HttpURLConnection;
8.29 +import java.net.URI;
8.30 +import java.net.URISyntaxException;
8.31 +import java.net.URL;
8.32 +import java.net.URLConnection;
8.33 +import java.util.Map;
8.34 +import net.java.html.BrwsrCtx;
8.35 +import net.java.html.js.JavaScriptBody;
8.36 +import org.apidesign.bck2brwsr.vmtest.VMTest;
8.37 +import org.apidesign.html.context.spi.Contexts;
8.38 +import org.apidesign.html.json.spi.Technology;
8.39 +import org.apidesign.html.json.spi.Transfer;
8.40 +import org.apidesign.html.json.tck.KOTest;
8.41 +import org.apidesign.html.json.tck.KnockoutTCK;
8.42 +import org.json.JSONException;
8.43 +import org.json.JSONObject;
8.44 +import org.openide.util.lookup.ServiceProvider;
8.45 +import org.testng.annotations.Factory;
8.46 +
8.47 +/**
8.48 + *
8.49 + * @author Jaroslav Tulach <jtulach@netbeans.org>
8.50 + */
8.51 +@ServiceProvider(service = KnockoutTCK.class)
8.52 +public final class KnockoutFXTest extends KnockoutTCK {
8.53 + public KnockoutFXTest() {
8.54 + }
8.55 +
8.56 + @Factory public static Object[] compatibilityTests() {
8.57 + return VMTest.newTests().
8.58 + withClasses(testClasses()).
8.59 + withTestAnnotation(KOTest.class).
8.60 + withLaunchers("fxbrwsr").build();
8.61 + }
8.62 +
8.63 + @Override
8.64 + public BrwsrCtx createContext() {
8.65 + FXContext fx = new FXContext();
8.66 + return Contexts.newBuilder().
8.67 + register(Technology.class, fx, 10).
8.68 + register(Transfer.class, fx, 10).
8.69 + build();
8.70 + }
8.71 +
8.72 + @Override
8.73 + public Object createJSON(Map<String, Object> values) {
8.74 + JSONObject json = new JSONObject();
8.75 + for (Map.Entry<String, Object> entry : values.entrySet()) {
8.76 + try {
8.77 + json.put(entry.getKey(), entry.getValue());
8.78 + } catch (JSONException ex) {
8.79 + throw new IllegalStateException(ex);
8.80 + }
8.81 + }
8.82 + return json;
8.83 + }
8.84 +
8.85 + @Override
8.86 + @JavaScriptBody(args = { "s", "args" }, body = ""
8.87 + + "var f = new Function(s); "
8.88 + + "return f.apply(null, args);"
8.89 + )
8.90 + public native Object executeScript(String script, Object[] arguments);
8.91 +
8.92 + @JavaScriptBody(args = { }, body =
8.93 + "var h;"
8.94 + + "if (!!window && !!window.location && !!window.location.href)\n"
8.95 + + " h = window.location.href;\n"
8.96 + + "else "
8.97 + + " h = null;"
8.98 + + "return h;\n"
8.99 + )
8.100 + private static native String findBaseURL();
8.101 +
8.102 + @Override
8.103 + public URI prepareURL(String content, String mimeType, String[] parameters) {
8.104 + try {
8.105 + final URL baseURL = new URL(findBaseURL());
8.106 + StringBuilder sb = new StringBuilder();
8.107 + sb.append("/dynamic?mimeType=").append(mimeType);
8.108 + for (int i = 0; i < parameters.length; i++) {
8.109 + sb.append("¶m" + i).append("=").append(parameters[i]);
8.110 + }
8.111 + String mangle = content.replace("\n", "%0a")
8.112 + .replace("\"", "\\\"").replace(" ", "%20");
8.113 + sb.append("&content=").append(mangle);
8.114 +
8.115 + URL query = new URL(baseURL, sb.toString());
8.116 + URLConnection c = query.openConnection();
8.117 + BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
8.118 + URI connectTo = new URI(br.readLine());
8.119 + return connectTo;
8.120 + } catch (IOException ex) {
8.121 + throw new IllegalStateException(ex);
8.122 + } catch (URISyntaxException ex) {
8.123 + throw new IllegalStateException(ex);
8.124 + }
8.125 + }
8.126 +}
9.1 --- a/ko/pom.xml Wed Jun 26 19:37:34 2013 +0200
9.2 +++ b/ko/pom.xml Wed Jun 26 19:57:38 2013 +0200
9.3 @@ -11,9 +11,13 @@
9.4 <artifactId>bck2brwsr</artifactId>
9.5 <version>0.8-SNAPSHOT</version>
9.6 </parent>
9.7 + <properties>
9.8 + <net.java.html.version>0.4-SNAPSHOT</net.java.html.version>
9.9 + </properties>
9.10 <modules>
9.11 <module>archetype</module>
9.12 <module>archetype-test</module>
9.13 <module>bck2brwsr</module>
9.14 + <module>fx</module>
9.15 </modules>
9.16 </project>
10.1 --- a/pom.xml Wed Jun 26 19:37:34 2013 +0200
10.2 +++ b/pom.xml Wed Jun 26 19:57:38 2013 +0200
10.3 @@ -92,7 +92,7 @@
10.4 <exclude>dew/src/main/resources/org/apidesign/bck2brwsr/dew/**</exclude>
10.5 <exclude>javaquery/api/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout*.js</exclude>
10.6 <exclude>ko/archetype/src/main/resources/archetype-resources/**</exclude>
10.7 - <exclude>ko/bck2brwsr/src/main/resources/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js</exclude>
10.8 + <exclude>ko/*/src/main/resources/org/apidesign/*/*/knockout-2.2.1.js</exclude>
10.9 </excludes>
10.10 </configuration>
10.11 </plugin>