1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/ko-fx/pom.xml Thu Apr 25 16:21:50 2013 +0200
1.3 @@ -0,0 +1,50 @@
1.4 +<?xml version="1.0"?>
1.5 +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
1.6 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1.7 + <modelVersion>4.0.0</modelVersion>
1.8 + <parent>
1.9 + <groupId>org.apidesign</groupId>
1.10 + <artifactId>html</artifactId>
1.11 + <version>0.1-SNAPSHOT</version>
1.12 + </parent>
1.13 + <groupId>org.apidesign.html</groupId>
1.14 + <artifactId>ko-fx</artifactId>
1.15 + <version>0.1-SNAPSHOT</version>
1.16 + <name>Knockout.fx</name>
1.17 + <url>http://maven.apache.org</url>
1.18 + <properties>
1.19 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
1.20 + </properties>
1.21 + <dependencies>
1.22 + <dependency>
1.23 + <groupId>com.oracle</groupId>
1.24 + <artifactId>javafx</artifactId>
1.25 + <version>2.2</version>
1.26 + <scope>system</scope>
1.27 + <systemPath>${java.home}/lib/jfxrt.jar</systemPath>
1.28 + </dependency>
1.29 + <dependency>
1.30 + <groupId>org.json</groupId>
1.31 + <artifactId>json</artifactId>
1.32 + <version>20090211</version>
1.33 + <type>jar</type>
1.34 + </dependency>
1.35 + <dependency>
1.36 + <groupId>org.apidesign.html</groupId>
1.37 + <artifactId>net.java.html.json</artifactId>
1.38 + <version>0.1-SNAPSHOT</version>
1.39 + </dependency>
1.40 + <dependency>
1.41 + <groupId>org.testng</groupId>
1.42 + <artifactId>testng</artifactId>
1.43 + <version>6.5.2</version>
1.44 + <scope>test</scope>
1.45 + </dependency>
1.46 + <dependency>
1.47 + <groupId>${project.groupId}</groupId>
1.48 + <artifactId>net.java.html.json.tck</artifactId>
1.49 + <version>${project.version}</version>
1.50 + <scope>test</scope>
1.51 + </dependency>
1.52 + </dependencies>
1.53 +</project>
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/Console.java Thu Apr 25 16:21:50 2013 +0200
2.3 @@ -0,0 +1,48 @@
2.4 +/**
2.5 + * HTML via Java(tm) Language Bindings
2.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
2.7 + *
2.8 + * This program is free software: you can redistribute it and/or modify
2.9 + * it under the terms of the GNU General Public License as published by
2.10 + * the Free Software Foundation, version 2 of the License.
2.11 + *
2.12 + * This program is distributed in the hope that it will be useful,
2.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
2.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2.15 + * GNU General Public License for more details. apidesign.org
2.16 + * designates this particular file as subject to the
2.17 + * "Classpath" exception as provided by apidesign.org
2.18 + * in the License file that accompanied this code.
2.19 + *
2.20 + * You should have received a copy of the GNU General Public License
2.21 + * along with this program. Look for COPYING file in the top folder.
2.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
2.23 + */
2.24 +package org.apidesign.html.kofx;
2.25 +
2.26 +import java.util.logging.Logger;
2.27 +import javafx.scene.web.WebEngine;
2.28 +import netscape.javascript.JSObject;
2.29 +
2.30 +/**
2.31 + *
2.32 + * @author Jaroslav Tulach <jtulach@netbeans.org>
2.33 + */
2.34 +public class Console {
2.35 + private static final Logger LOG = Logger.getLogger(Console.class.getName());
2.36 +
2.37 + private Console() {
2.38 + }
2.39 +
2.40 + static void register(WebEngine web) {
2.41 + ((JSObject)web.executeScript("window")).setMember("jconsole", new Console());
2.42 + web.executeScript("console.log = function(m) { jconsole.log(m); };");
2.43 + web.executeScript("console.info = function(m) { jconsole.log(m); };");
2.44 + web.executeScript("console.error = function(m) { jconsole.log(m); };");
2.45 + web.executeScript("console.warn = function(m) { jconsole.log(m); };");
2.46 + }
2.47 +
2.48 + public void log(String msg) {
2.49 + LOG.info(msg);
2.50 + }
2.51 +}
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/FXContext.java Thu Apr 25 16:21:50 2013 +0200
3.3 @@ -0,0 +1,89 @@
3.4 +/**
3.5 + * HTML via Java(tm) Language Bindings
3.6 + * Copyright (C) 2013 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. apidesign.org
3.16 + * designates this particular file as subject to the
3.17 + * "Classpath" exception as provided by apidesign.org
3.18 + * in the License file that accompanied this code.
3.19 + *
3.20 + * You should have received a copy of the GNU General Public License
3.21 + * along with this program. Look for COPYING file in the top folder.
3.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
3.23 + */
3.24 +package org.apidesign.html.kofx;
3.25 +
3.26 +import java.util.concurrent.Callable;
3.27 +import java.util.logging.Logger;
3.28 +import net.java.html.json.Context;
3.29 +import netscape.javascript.JSObject;
3.30 +import org.apidesign.html.json.spi.ContextBuilder;
3.31 +import org.apidesign.html.json.spi.FunctionBinding;
3.32 +import org.apidesign.html.json.spi.JSONCall;
3.33 +import org.apidesign.html.json.spi.PropertyBinding;
3.34 +import org.apidesign.html.json.spi.Technology;
3.35 +import org.apidesign.html.json.spi.Transfer;
3.36 +
3.37 +/**
3.38 + *
3.39 + * @author Jaroslav Tulach <jtulach@netbeans.org>
3.40 + */
3.41 +public final class FXContext implements Callable<Context>, Technology<JSObject>, Transfer {
3.42 + static final Logger LOG = Logger.getLogger(FXContext.class.getName());
3.43 +
3.44 +
3.45 + @Override
3.46 + public Context call() throws Exception {
3.47 + return ContextBuilder.create().withTechnology(this).
3.48 + withTransfer(this).build();
3.49 + }
3.50 +
3.51 + @Override
3.52 + public JSObject wrapModel(Object model) {
3.53 + return (JSObject) Knockout.createBinding(model).koData();
3.54 + }
3.55 +
3.56 + @Override
3.57 + public void bind(PropertyBinding b, Object model, JSObject data) {
3.58 + final boolean isList = false;
3.59 + final boolean isPrimitive = false;
3.60 + Knockout.bind(data, model, b, isPrimitive, isList);
3.61 + }
3.62 +
3.63 + @Override
3.64 + public void valueHasMutated(JSObject data, String propertyName) {
3.65 + Knockout.valueHasMutated(data, propertyName);
3.66 + }
3.67 +
3.68 + @Override
3.69 + public void expose(FunctionBinding fb, Object model, JSObject d) {
3.70 + Knockout.expose(d, fb);
3.71 + }
3.72 +
3.73 + @Override
3.74 + public void applyBindings(JSObject data) {
3.75 + Knockout.applyBindings(data);
3.76 + }
3.77 +
3.78 + @Override
3.79 + public Object wrapArray(Object[] arr) {
3.80 + return Knockout.toArray(arr);
3.81 + }
3.82 +
3.83 + @Override
3.84 + public void extract(Object obj, String[] props, Object[] values) {
3.85 + LoadJSON.extractJSON(obj, props, values);
3.86 + }
3.87 +
3.88 + @Override
3.89 + public void loadJSON(final JSONCall call) {
3.90 + LoadJSON.loadJSON(call);
3.91 + }
3.92 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/Knockout.java Thu Apr 25 16:21:50 2013 +0200
4.3 @@ -0,0 +1,196 @@
4.4 +/**
4.5 + * HTML via Java(tm) Language Bindings
4.6 + * Copyright (C) 2013 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. apidesign.org
4.16 + * designates this particular file as subject to the
4.17 + * "Classpath" exception as provided by apidesign.org
4.18 + * in the License file that accompanied this code.
4.19 + *
4.20 + * You should have received a copy of the GNU General Public License
4.21 + * along with this program. Look for COPYING file in the top folder.
4.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
4.23 + */
4.24 +package org.apidesign.html.kofx;
4.25 +
4.26 +import java.io.BufferedReader;
4.27 +import java.io.IOException;
4.28 +import java.io.InputStream;
4.29 +import java.io.InputStreamReader;
4.30 +import java.util.logging.Level;
4.31 +import java.util.logging.Logger;
4.32 +import javafx.scene.web.WebEngine;
4.33 +import net.java.html.json.Model;
4.34 +import netscape.javascript.JSObject;
4.35 +import org.apidesign.html.json.spi.FunctionBinding;
4.36 +import org.apidesign.html.json.spi.PropertyBinding;
4.37 +
4.38 +/** Provides binding between {@link Model models} and knockout.js running
4.39 + * inside a JavaFX WebView.
4.40 + *
4.41 + * @author Jaroslav Tulach <jtulach@netbeans.org>
4.42 + */
4.43 +public final class Knockout {
4.44 + private static final Logger LOG = Logger.getLogger(Knockout.class.getName());
4.45 + /** used by tests */
4.46 + static Knockout next;
4.47 + private final Object model;
4.48 +
4.49 + Knockout(Object model) {
4.50 + this.model = model == null ? this : model;
4.51 + }
4.52 +
4.53 + public Object koData() {
4.54 + return model;
4.55 + }
4.56 +
4.57 + static Object toArray(Object[] arr) {
4.58 + return InvokeJS.KObject.call("array", arr);
4.59 + }
4.60 +
4.61 + public static <M> Knockout createBinding(Object model) {
4.62 + Object bindings = InvokeJS.KObject.call("create", model);
4.63 + return new Knockout(bindings);
4.64 + }
4.65 +
4.66 + public void valueHasMutated(String prop) {
4.67 + valueHasMutated((JSObject) model, prop);
4.68 + }
4.69 + public static void valueHasMutated(JSObject model, String prop) {
4.70 + LOG.log(Level.FINE, "property mutated: {0}", prop);
4.71 + try {
4.72 + JSObject koProp = (JSObject) ((JSObject) model).getMember(prop);
4.73 + koProp.call("valueHasMutated");
4.74 + } catch (Throwable t) {
4.75 + LOG.log(Level.WARNING, "valueHasMutated failed for {0}", model);
4.76 + }
4.77 + }
4.78 +
4.79 + static void bind(
4.80 + Object bindings, Object model, PropertyBinding pb, boolean primitive, boolean array
4.81 + ) {
4.82 + WebEngine e = web();
4.83 + if (e == null) {
4.84 + return;
4.85 + }
4.86 +
4.87 + final String prop = pb.getPropertyName();
4.88 + try {
4.89 + InvokeJS.KObject.call("bind", bindings, pb, prop, "getValue", pb.isReadOnly() ? null : "setValue", primitive, array);
4.90 +
4.91 + ((JSObject)bindings).setMember("koModel", model);
4.92 + LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
4.93 + } catch (Throwable ex) {
4.94 + LOG.log(Level.WARNING, "binding failed for {0} on {1}", new Object[]{prop, bindings});
4.95 + }
4.96 + }
4.97 + static void expose(Object bindings, FunctionBinding f) {
4.98 + WebEngine e = web();
4.99 + if (e == null) {
4.100 + return;
4.101 + }
4.102 + final String prop = f.getFunctionName();
4.103 + try {
4.104 + InvokeJS.KObject.call("expose", bindings, f, prop, "call");
4.105 + } catch (Throwable ex) {
4.106 + LOG.log(Level.SEVERE, "Cannot define binding for " + prop + " in model " + f, ex);
4.107 + }
4.108 + }
4.109 +
4.110 + static void applyBindings(Object bindings) {
4.111 + if (web() != null) {
4.112 + JSObject ko = (JSObject) web().executeScript("ko");
4.113 + ko.call("applyBindings", bindings);
4.114 + }
4.115 + }
4.116 +
4.117 + static WebEngine web() {
4.118 + return (WebEngine) System.getProperties().get("webEngine");
4.119 + }
4.120 +
4.121 +
4.122 + private static final class InvokeJS {
4.123 + static final JSObject KObject;
4.124 +
4.125 + static {
4.126 + final InputStream koScript = Knockout.class.getResourceAsStream("knockout-2.2.1.js");
4.127 + assert koScript != null : "Can't load knockout.js";
4.128 + BufferedReader r = new BufferedReader(new InputStreamReader(koScript));
4.129 + StringBuilder sb = new StringBuilder();
4.130 + for (;;) {
4.131 + try {
4.132 + String l = r.readLine();
4.133 + if (l == null) {
4.134 + break;
4.135 + }
4.136 + sb.append(l).append('\n');
4.137 + } catch (IOException ex) {
4.138 + throw new IllegalStateException(ex);
4.139 + }
4.140 + }
4.141 + web().executeScript(sb.toString());
4.142 + Object ko = web().executeScript("ko");
4.143 + assert ko != null : "Knockout library successfully defined 'ko'";
4.144 +
4.145 + Console.register(web());
4.146 + KObject = (JSObject) web().executeScript(
4.147 + "(function(scope) {"
4.148 + + " var kCnt = 0; "
4.149 + + " scope.KObject = {};"
4.150 + + " scope.KObject.create= function(value) {"
4.151 + + " var cnt = ++kCnt;"
4.152 + + " var ret = {};"
4.153 + + " ret.toString = function() { return 'KObject' + cnt + ' value: ' + value + ' props: ' + Object.keys(this); };"
4.154 + + " return ret;"
4.155 + + " };"
4.156 + + " scope.KObject.array= function() {"
4.157 + + " return Array.prototype.slice.call(arguments);"
4.158 + + " };"
4.159 + + " scope.KObject.expose = function(bindings, model, prop, sig) {"
4.160 + + " bindings[prop] = function(data, ev) {"
4.161 + // + " console.log(\" callback on prop: \" + prop);"
4.162 + + " model[sig](data, ev);"
4.163 + + " };"
4.164 + + " };"
4.165 + + " scope.KObject.bind = function(bindings, model, prop, getter, setter, primitive, array) {"
4.166 + + " var bnd = {"
4.167 + + " read: function() {"
4.168 + + " try {"
4.169 + + " var v = model[getter]();"
4.170 + // + " console.log(\" getter value \" + v + \" for property \" + prop);"
4.171 + // + " try { v = v.koData(); } catch (ignore) {"
4.172 + // + " console.log(\"Cannot convert to koData: \" + ignore);"
4.173 + // + " };"
4.174 + // + " console.log(\" getter ret value \" + v);"
4.175 + // + " for (var pn in v) {"
4.176 + // + " console.log(\" prop: \" + pn + \" + in + \" + v + \" = \" + v[pn]);"
4.177 + // + " if (typeof v[pn] == \"function\") console.log(\" its function value:\" + v[pn]());"
4.178 + // + " }"
4.179 + // + " console.log(\" all props printed for \" + (typeof v));"
4.180 + + " return v;"
4.181 + + " } catch (e) {"
4.182 + + " alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
4.183 + + " }"
4.184 + + " },"
4.185 + + " owner: bindings"
4.186 + // + " ,deferEvaluation: true"
4.187 + + " };"
4.188 + + " if (setter != null) {"
4.189 + + " bnd.write = function(val) {"
4.190 + + " model[setter](primitive ? new Number(val) : val);"
4.191 + + " };"
4.192 + + " };"
4.193 + + " bindings[prop] = ko.computed(bnd);"
4.194 + + " };"
4.195 + + "})(window); window.KObject");
4.196 + }
4.197 +
4.198 + }
4.199 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/LoadJSON.java Thu Apr 25 16:21:50 2013 +0200
5.3 @@ -0,0 +1,182 @@
5.4 +/**
5.5 + * HTML via Java(tm) Language Bindings
5.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5.7 + *
5.8 + * This program is free software: you can redistribute it and/or modify
5.9 + * it under the terms of the GNU General Public License as published by
5.10 + * the Free Software Foundation, version 2 of the License.
5.11 + *
5.12 + * This program is distributed in the hope that it will be useful,
5.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
5.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5.15 + * GNU General Public License for more details. apidesign.org
5.16 + * designates this particular file as subject to the
5.17 + * "Classpath" exception as provided by apidesign.org
5.18 + * in the License file that accompanied this code.
5.19 + *
5.20 + * You should have received a copy of the GNU General Public License
5.21 + * along with this program. Look for COPYING file in the top folder.
5.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
5.23 + */
5.24 +package org.apidesign.html.kofx;
5.25 +
5.26 +import java.io.IOException;
5.27 +import java.io.InputStreamReader;
5.28 +import java.io.PushbackInputStream;
5.29 +import java.io.Reader;
5.30 +import java.net.MalformedURLException;
5.31 +import java.net.URL;
5.32 +import java.util.Iterator;
5.33 +import java.util.concurrent.Executor;
5.34 +import java.util.concurrent.Executors;
5.35 +import java.util.logging.Level;
5.36 +import java.util.logging.Logger;
5.37 +import javafx.application.Platform;
5.38 +import javafx.scene.web.WebEngine;
5.39 +import netscape.javascript.JSObject;
5.40 +import org.apidesign.html.json.spi.JSONCall;
5.41 +import org.json.JSONArray;
5.42 +import org.json.JSONException;
5.43 +import org.json.JSONObject;
5.44 +import org.json.JSONTokener;
5.45 +
5.46 +/**
5.47 + *
5.48 + * @author Jaroslav Tulach <jtulach@netbeans.org>
5.49 + */
5.50 +final class LoadJSON implements Runnable {
5.51 + private static final Logger LOG = FXContext.LOG;
5.52 + private static final Executor REQ = Executors.newCachedThreadPool();
5.53 +
5.54 + private final JSONCall call;
5.55 + private final URL base;
5.56 + private Throwable error;
5.57 + private Object json;
5.58 +
5.59 +
5.60 + private LoadJSON(JSONCall call) {
5.61 + this.call = call;
5.62 + URL b;
5.63 + try {
5.64 + b = new URL(findBaseURL());
5.65 + } catch (MalformedURLException ex) {
5.66 + LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
5.67 + b = null;
5.68 + }
5.69 + this.base = b;
5.70 + }
5.71 +
5.72 + public static void loadJSON(JSONCall call) {
5.73 + REQ.execute(new LoadJSON((call)));
5.74 + }
5.75 +
5.76 + @Override
5.77 + public void run() {
5.78 + if (Platform.isFxApplicationThread()) {
5.79 + if (error != null) {
5.80 + call.notifyError(error);
5.81 + } else {
5.82 + call.notifySuccess(json);
5.83 + }
5.84 + return;
5.85 + }
5.86 + final String url;
5.87 + if (call.isJSONP()) {
5.88 + url = call.composeURL("dummy");
5.89 + } else {
5.90 + url = call.composeURL(null);
5.91 + }
5.92 + try {
5.93 + final URL u = new URL(base, url.replace(" ", "%20"));
5.94 + final PushbackInputStream is = new PushbackInputStream(u.openStream(), 1);
5.95 + boolean array = false;
5.96 + if (call.isJSONP()) {
5.97 + for (;;) {
5.98 + int ch = is.read();
5.99 + if (ch == -1) {
5.100 + break;
5.101 + }
5.102 + if (ch == '[') {
5.103 + is.unread(ch);
5.104 + array = true;
5.105 + break;
5.106 + }
5.107 + if (ch == '{') {
5.108 + is.unread(ch);
5.109 + break;
5.110 + }
5.111 + }
5.112 + } else {
5.113 + int ch = is.read();
5.114 + array = ch == '[';
5.115 + is.unread(ch);
5.116 + }
5.117 + Reader r = new InputStreamReader(is, "UTF-8");
5.118 +
5.119 + JSONTokener tok = new JSONTokener(r);
5.120 + Object obj = array ? new JSONArray(tok) : new JSONObject(tok);
5.121 + json = convertToArray(obj);
5.122 + } catch (JSONException | IOException ex) {
5.123 + error = ex;
5.124 + LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
5.125 + } finally {
5.126 + Platform.runLater(this);
5.127 + }
5.128 + }
5.129 +
5.130 + private static Object convertToArray(Object o) throws JSONException {
5.131 + if (o instanceof JSONArray) {
5.132 + JSONArray ja = (JSONArray)o;
5.133 + Object[] arr = new Object[ja.length()];
5.134 + for (int i = 0; i < arr.length; i++) {
5.135 + arr[i] = convertToArray(ja.get(i));
5.136 + }
5.137 + return arr;
5.138 + } else if (o instanceof JSONObject) {
5.139 + JSONObject obj = (JSONObject)o;
5.140 + Iterator it = obj.keys();
5.141 + while (it.hasNext()) {
5.142 + String key = (String)it.next();
5.143 + obj.put(key, convertToArray(obj.get(key)));
5.144 + }
5.145 + return obj;
5.146 + } else {
5.147 + return o;
5.148 + }
5.149 + }
5.150 +
5.151 + public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
5.152 + if (jsonObject instanceof JSONObject) {
5.153 + JSONObject obj = (JSONObject)jsonObject;
5.154 + for (int i = 0; i < props.length; i++) {
5.155 + try {
5.156 + values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
5.157 + } catch (JSONException ex) {
5.158 + LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
5.159 + }
5.160 + }
5.161 + }
5.162 + if (jsonObject instanceof JSObject) {
5.163 + JSObject obj = (JSObject)jsonObject;
5.164 + for (int i = 0; i < props.length; i++) {
5.165 + Object val = obj.getMember(props[i]);
5.166 + values[i] = isDefined(val) ? val : null;
5.167 + }
5.168 + }
5.169 + }
5.170 +
5.171 + private static String findBaseURL() {
5.172 + WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
5.173 + return (String) eng.executeScript(
5.174 + "var h;"
5.175 + + "if (!!window && !!window.location && !!window.location.href)\n"
5.176 + + " h = window.location.href;\n"
5.177 + + "else "
5.178 + + " h = null;"
5.179 + + "h\n");
5.180 + }
5.181 +
5.182 + private static boolean isDefined(Object val) {
5.183 + return !"undefined".equals(val);
5.184 + }
5.185 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/ko-fx/src/main/resources/org/apidesign/html/kofx/knockout-2.2.1.js Thu Apr 25 16:21:50 2013 +0200
6.3 @@ -0,0 +1,3594 @@
6.4 +// Knockout JavaScript library v2.2.1
6.5 +// (c) Steven Sanderson - http://knockoutjs.com/
6.6 +// License: MIT (http://www.opensource.org/licenses/mit-license.php)
6.7 +
6.8 +(function(){
6.9 +var DEBUG=true;
6.10 +(function(window,document,navigator,jQuery,undefined){
6.11 +!function(factory) {
6.12 + // Support three module loading scenarios
6.13 + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
6.14 + // [1] CommonJS/Node.js
6.15 + var target = module['exports'] || exports; // module.exports is for Node.js
6.16 + factory(target);
6.17 + } else if (typeof define === 'function' && define['amd']) {
6.18 + // [2] AMD anonymous module
6.19 + define(['exports'], factory);
6.20 + } else {
6.21 + // [3] No module loader (plain <script> tag) - put directly in global namespace
6.22 + factory(window['ko'] = {});
6.23 + }
6.24 +}(function(koExports){
6.25 +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
6.26 +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
6.27 +var ko = typeof koExports !== 'undefined' ? koExports : {};
6.28 +// Google Closure Compiler helpers (used only to make the minified file smaller)
6.29 +ko.exportSymbol = function(koPath, object) {
6.30 + var tokens = koPath.split(".");
6.31 +
6.32 + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
6.33 + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
6.34 + var target = ko;
6.35 +
6.36 + for (var i = 0; i < tokens.length - 1; i++)
6.37 + target = target[tokens[i]];
6.38 + target[tokens[tokens.length - 1]] = object;
6.39 +};
6.40 +ko.exportProperty = function(owner, publicName, object) {
6.41 + owner[publicName] = object;
6.42 +};
6.43 +ko.version = "2.2.1";
6.44 +
6.45 +ko.exportSymbol('version', ko.version);
6.46 +ko.utils = new (function () {
6.47 + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
6.48 +
6.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)
6.50 + var knownEvents = {}, knownEventTypesByEventName = {};
6.51 + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents';
6.52 + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
6.53 + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
6.54 + for (var eventType in knownEvents) {
6.55 + var knownEventsForType = knownEvents[eventType];
6.56 + if (knownEventsForType.length) {
6.57 + for (var i = 0, j = knownEventsForType.length; i < j; i++)
6.58 + knownEventTypesByEventName[knownEventsForType[i]] = eventType;
6.59 + }
6.60 + }
6.61 + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
6.62 +
6.63 + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
6.64 + // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
6.65 + // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
6.66 + // If there is a future need to detect specific versions of IE10+, we will amend this.
6.67 + var ieVersion = (function() {
6.68 + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
6.69 +
6.70 + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
6.71 + while (
6.72 + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
6.73 + iElems[0]
6.74 + );
6.75 + return version > 4 ? version : undefined;
6.76 + }());
6.77 + var isIe6 = ieVersion === 6,
6.78 + isIe7 = ieVersion === 7;
6.79 +
6.80 + function isClickOnCheckableElement(element, eventType) {
6.81 + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
6.82 + if (eventType.toLowerCase() != "click") return false;
6.83 + var inputType = element.type;
6.84 + return (inputType == "checkbox") || (inputType == "radio");
6.85 + }
6.86 +
6.87 + return {
6.88 + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
6.89 +
6.90 + arrayForEach: function (array, action) {
6.91 + for (var i = 0, j = array.length; i < j; i++)
6.92 + action(array[i]);
6.93 + },
6.94 +
6.95 + arrayIndexOf: function (array, item) {
6.96 + if (typeof Array.prototype.indexOf == "function")
6.97 + return Array.prototype.indexOf.call(array, item);
6.98 + for (var i = 0, j = array.length; i < j; i++)
6.99 + if (array[i] === item)
6.100 + return i;
6.101 + return -1;
6.102 + },
6.103 +
6.104 + arrayFirst: function (array, predicate, predicateOwner) {
6.105 + for (var i = 0, j = array.length; i < j; i++)
6.106 + if (predicate.call(predicateOwner, array[i]))
6.107 + return array[i];
6.108 + return null;
6.109 + },
6.110 +
6.111 + arrayRemoveItem: function (array, itemToRemove) {
6.112 + var index = ko.utils.arrayIndexOf(array, itemToRemove);
6.113 + if (index >= 0)
6.114 + array.splice(index, 1);
6.115 + },
6.116 +
6.117 + arrayGetDistinctValues: function (array) {
6.118 + array = array || [];
6.119 + var result = [];
6.120 + for (var i = 0, j = array.length; i < j; i++) {
6.121 + if (ko.utils.arrayIndexOf(result, array[i]) < 0)
6.122 + result.push(array[i]);
6.123 + }
6.124 + return result;
6.125 + },
6.126 +
6.127 + arrayMap: function (array, mapping) {
6.128 + array = array || [];
6.129 + var result = [];
6.130 + for (var i = 0, j = array.length; i < j; i++)
6.131 + result.push(mapping(array[i]));
6.132 + return result;
6.133 + },
6.134 +
6.135 + arrayFilter: function (array, predicate) {
6.136 + array = array || [];
6.137 + var result = [];
6.138 + for (var i = 0, j = array.length; i < j; i++)
6.139 + if (predicate(array[i]))
6.140 + result.push(array[i]);
6.141 + return result;
6.142 + },
6.143 +
6.144 + arrayPushAll: function (array, valuesToPush) {
6.145 + if (valuesToPush instanceof Array)
6.146 + array.push.apply(array, valuesToPush);
6.147 + else
6.148 + for (var i = 0, j = valuesToPush.length; i < j; i++)
6.149 + array.push(valuesToPush[i]);
6.150 + return array;
6.151 + },
6.152 +
6.153 + extend: function (target, source) {
6.154 + if (source) {
6.155 + for(var prop in source) {
6.156 + if(source.hasOwnProperty(prop)) {
6.157 + target[prop] = source[prop];
6.158 + }
6.159 + }
6.160 + }
6.161 + return target;
6.162 + },
6.163 +
6.164 + emptyDomNode: function (domNode) {
6.165 + while (domNode.firstChild) {
6.166 + ko.removeNode(domNode.firstChild);
6.167 + }
6.168 + },
6.169 +
6.170 + moveCleanedNodesToContainerElement: function(nodes) {
6.171 + // Ensure it's a real array, as we're about to reparent the nodes and
6.172 + // we don't want the underlying collection to change while we're doing that.
6.173 + var nodesArray = ko.utils.makeArray(nodes);
6.174 +
6.175 + var container = document.createElement('div');
6.176 + for (var i = 0, j = nodesArray.length; i < j; i++) {
6.177 + container.appendChild(ko.cleanNode(nodesArray[i]));
6.178 + }
6.179 + return container;
6.180 + },
6.181 +
6.182 + cloneNodes: function (nodesArray, shouldCleanNodes) {
6.183 + for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
6.184 + var clonedNode = nodesArray[i].cloneNode(true);
6.185 + newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
6.186 + }
6.187 + return newNodesArray;
6.188 + },
6.189 +
6.190 + setDomNodeChildren: function (domNode, childNodes) {
6.191 + ko.utils.emptyDomNode(domNode);
6.192 + if (childNodes) {
6.193 + for (var i = 0, j = childNodes.length; i < j; i++)
6.194 + domNode.appendChild(childNodes[i]);
6.195 + }
6.196 + },
6.197 +
6.198 + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
6.199 + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
6.200 + if (nodesToReplaceArray.length > 0) {
6.201 + var insertionPoint = nodesToReplaceArray[0];
6.202 + var parent = insertionPoint.parentNode;
6.203 + for (var i = 0, j = newNodesArray.length; i < j; i++)
6.204 + parent.insertBefore(newNodesArray[i], insertionPoint);
6.205 + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
6.206 + ko.removeNode(nodesToReplaceArray[i]);
6.207 + }
6.208 + }
6.209 + },
6.210 +
6.211 + setOptionNodeSelectionState: function (optionNode, isSelected) {
6.212 + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
6.213 + if (ieVersion < 7)
6.214 + optionNode.setAttribute("selected", isSelected);
6.215 + else
6.216 + optionNode.selected = isSelected;
6.217 + },
6.218 +
6.219 + stringTrim: function (string) {
6.220 + return (string || "").replace(stringTrimRegex, "");
6.221 + },
6.222 +
6.223 + stringTokenize: function (string, delimiter) {
6.224 + var result = [];
6.225 + var tokens = (string || "").split(delimiter);
6.226 + for (var i = 0, j = tokens.length; i < j; i++) {
6.227 + var trimmed = ko.utils.stringTrim(tokens[i]);
6.228 + if (trimmed !== "")
6.229 + result.push(trimmed);
6.230 + }
6.231 + return result;
6.232 + },
6.233 +
6.234 + stringStartsWith: function (string, startsWith) {
6.235 + string = string || "";
6.236 + if (startsWith.length > string.length)
6.237 + return false;
6.238 + return string.substring(0, startsWith.length) === startsWith;
6.239 + },
6.240 +
6.241 + domNodeIsContainedBy: function (node, containedByNode) {
6.242 + if (containedByNode.compareDocumentPosition)
6.243 + return (containedByNode.compareDocumentPosition(node) & 16) == 16;
6.244 + while (node != null) {
6.245 + if (node == containedByNode)
6.246 + return true;
6.247 + node = node.parentNode;
6.248 + }
6.249 + return false;
6.250 + },
6.251 +
6.252 + domNodeIsAttachedToDocument: function (node) {
6.253 + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument);
6.254 + },
6.255 +
6.256 + tagNameLower: function(element) {
6.257 + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
6.258 + // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
6.259 + // we don't need to do the .toLowerCase() as it will always be lower case anyway.
6.260 + return element && element.tagName && element.tagName.toLowerCase();
6.261 + },
6.262 +
6.263 + registerEventHandler: function (element, eventType, handler) {
6.264 + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
6.265 + if (!mustUseAttachEvent && typeof jQuery != "undefined") {
6.266 + if (isClickOnCheckableElement(element, eventType)) {
6.267 + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way:
6.268 + // it toggles the element checked state *after* the click event handlers run, whereas native
6.269 + // click events toggle the checked state *before* the event handler.
6.270 + // Fix this by intecepting the handler and applying the correct checkedness before it runs.
6.271 + var originalHandler = handler;
6.272 + handler = function(event, eventData) {
6.273 + var jQuerySuppliedCheckedState = this.checked;
6.274 + if (eventData)
6.275 + this.checked = eventData.checkedStateBeforeEvent !== true;
6.276 + originalHandler.call(this, event);
6.277 + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied
6.278 + };
6.279 + }
6.280 + jQuery(element)['bind'](eventType, handler);
6.281 + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
6.282 + element.addEventListener(eventType, handler, false);
6.283 + else if (typeof element.attachEvent != "undefined")
6.284 + element.attachEvent("on" + eventType, function (event) {
6.285 + handler.call(element, event);
6.286 + });
6.287 + else
6.288 + throw new Error("Browser doesn't support addEventListener or attachEvent");
6.289 + },
6.290 +
6.291 + triggerEvent: function (element, eventType) {
6.292 + if (!(element && element.nodeType))
6.293 + throw new Error("element must be a DOM node when calling triggerEvent");
6.294 +
6.295 + if (typeof jQuery != "undefined") {
6.296 + var eventData = [];
6.297 + if (isClickOnCheckableElement(element, eventType)) {
6.298 + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler
6.299 + eventData.push({ checkedStateBeforeEvent: element.checked });
6.300 + }
6.301 + jQuery(element)['trigger'](eventType, eventData);
6.302 + } else if (typeof document.createEvent == "function") {
6.303 + if (typeof element.dispatchEvent == "function") {
6.304 + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
6.305 + var event = document.createEvent(eventCategory);
6.306 + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
6.307 + element.dispatchEvent(event);
6.308 + }
6.309 + else
6.310 + throw new Error("The supplied element doesn't support dispatchEvent");
6.311 + } else if (typeof element.fireEvent != "undefined") {
6.312 + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event
6.313 + // so to make it consistent, we'll do it manually here
6.314 + if (isClickOnCheckableElement(element, eventType))
6.315 + element.checked = element.checked !== true;
6.316 + element.fireEvent("on" + eventType);
6.317 + }
6.318 + else
6.319 + throw new Error("Browser doesn't support triggering events");
6.320 + },
6.321 +
6.322 + unwrapObservable: function (value) {
6.323 + return ko.isObservable(value) ? value() : value;
6.324 + },
6.325 +
6.326 + peekObservable: function (value) {
6.327 + return ko.isObservable(value) ? value.peek() : value;
6.328 + },
6.329 +
6.330 + toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
6.331 + if (classNames) {
6.332 + var cssClassNameRegex = /[\w-]+/g,
6.333 + currentClassNames = node.className.match(cssClassNameRegex) || [];
6.334 + ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
6.335 + var indexOfClass = ko.utils.arrayIndexOf(currentClassNames, className);
6.336 + if (indexOfClass >= 0) {
6.337 + if (!shouldHaveClass)
6.338 + currentClassNames.splice(indexOfClass, 1);
6.339 + } else {
6.340 + if (shouldHaveClass)
6.341 + currentClassNames.push(className);
6.342 + }
6.343 + });
6.344 + node.className = currentClassNames.join(" ");
6.345 + }
6.346 + },
6.347 +
6.348 + setTextContent: function(element, textContent) {
6.349 + var value = ko.utils.unwrapObservable(textContent);
6.350 + if ((value === null) || (value === undefined))
6.351 + value = "";
6.352 +
6.353 + if (element.nodeType === 3) {
6.354 + element.data = value;
6.355 + } else {
6.356 + // We need there to be exactly one child: a text node.
6.357 + // If there are no children, more than one, or if it's not a text node,
6.358 + // we'll clear everything and create a single text node.
6.359 + var innerTextNode = ko.virtualElements.firstChild(element);
6.360 + if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
6.361 + ko.virtualElements.setDomNodeChildren(element, [document.createTextNode(value)]);
6.362 + } else {
6.363 + innerTextNode.data = value;
6.364 + }
6.365 +
6.366 + ko.utils.forceRefresh(element);
6.367 + }
6.368 + },
6.369 +
6.370 + setElementName: function(element, name) {
6.371 + element.name = name;
6.372 +
6.373 + // Workaround IE 6/7 issue
6.374 + // - https://github.com/SteveSanderson/knockout/issues/197
6.375 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
6.376 + if (ieVersion <= 7) {
6.377 + try {
6.378 + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
6.379 + }
6.380 + catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
6.381 + }
6.382 + },
6.383 +
6.384 + forceRefresh: function(node) {
6.385 + // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
6.386 + if (ieVersion >= 9) {
6.387 + // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
6.388 + var elem = node.nodeType == 1 ? node : node.parentNode;
6.389 + if (elem.style)
6.390 + elem.style.zoom = elem.style.zoom;
6.391 + }
6.392 + },
6.393 +
6.394 + ensureSelectElementIsRenderedCorrectly: function(selectElement) {
6.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.
6.396 + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
6.397 + if (ieVersion >= 9) {
6.398 + var originalWidth = selectElement.style.width;
6.399 + selectElement.style.width = 0;
6.400 + selectElement.style.width = originalWidth;
6.401 + }
6.402 + },
6.403 +
6.404 + range: function (min, max) {
6.405 + min = ko.utils.unwrapObservable(min);
6.406 + max = ko.utils.unwrapObservable(max);
6.407 + var result = [];
6.408 + for (var i = min; i <= max; i++)
6.409 + result.push(i);
6.410 + return result;
6.411 + },
6.412 +
6.413 + makeArray: function(arrayLikeObject) {
6.414 + var result = [];
6.415 + for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
6.416 + result.push(arrayLikeObject[i]);
6.417 + };
6.418 + return result;
6.419 + },
6.420 +
6.421 + isIe6 : isIe6,
6.422 + isIe7 : isIe7,
6.423 + ieVersion : ieVersion,
6.424 +
6.425 + getFormFields: function(form, fieldName) {
6.426 + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
6.427 + var isMatchingField = (typeof fieldName == 'string')
6.428 + ? function(field) { return field.name === fieldName }
6.429 + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
6.430 + var matches = [];
6.431 + for (var i = fields.length - 1; i >= 0; i--) {
6.432 + if (isMatchingField(fields[i]))
6.433 + matches.push(fields[i]);
6.434 + };
6.435 + return matches;
6.436 + },
6.437 +
6.438 + parseJson: function (jsonString) {
6.439 + if (typeof jsonString == "string") {
6.440 + jsonString = ko.utils.stringTrim(jsonString);
6.441 + if (jsonString) {
6.442 + if (window.JSON && window.JSON.parse) // Use native parsing where available
6.443 + return window.JSON.parse(jsonString);
6.444 + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
6.445 + }
6.446 + }
6.447 + return null;
6.448 + },
6.449 +
6.450 + stringifyJson: function (data, replacer, space) { // replacer and space are optional
6.451 + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined"))
6.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");
6.453 + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
6.454 + },
6.455 +
6.456 + postJson: function (urlOrForm, data, options) {
6.457 + options = options || {};
6.458 + var params = options['params'] || {};
6.459 + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
6.460 + var url = urlOrForm;
6.461 +
6.462 + // If we were given a form, use its 'action' URL and pick out any requested field values
6.463 + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
6.464 + var originalForm = urlOrForm;
6.465 + url = originalForm.action;
6.466 + for (var i = includeFields.length - 1; i >= 0; i--) {
6.467 + var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
6.468 + for (var j = fields.length - 1; j >= 0; j--)
6.469 + params[fields[j].name] = fields[j].value;
6.470 + }
6.471 + }
6.472 +
6.473 + data = ko.utils.unwrapObservable(data);
6.474 + var form = document.createElement("form");
6.475 + form.style.display = "none";
6.476 + form.action = url;
6.477 + form.method = "post";
6.478 + for (var key in data) {
6.479 + var input = document.createElement("input");
6.480 + input.name = key;
6.481 + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
6.482 + form.appendChild(input);
6.483 + }
6.484 + for (var key in params) {
6.485 + var input = document.createElement("input");
6.486 + input.name = key;
6.487 + input.value = params[key];
6.488 + form.appendChild(input);
6.489 + }
6.490 + document.body.appendChild(form);
6.491 + options['submitter'] ? options['submitter'](form) : form.submit();
6.492 + setTimeout(function () { form.parentNode.removeChild(form); }, 0);
6.493 + }
6.494 + }
6.495 +})();
6.496 +
6.497 +ko.exportSymbol('utils', ko.utils);
6.498 +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
6.499 +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
6.500 +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
6.501 +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
6.502 +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
6.503 +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
6.504 +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
6.505 +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
6.506 +ko.exportSymbol('utils.extend', ko.utils.extend);
6.507 +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
6.508 +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
6.509 +ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
6.510 +ko.exportSymbol('utils.postJson', ko.utils.postJson);
6.511 +ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
6.512 +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
6.513 +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
6.514 +ko.exportSymbol('utils.range', ko.utils.range);
6.515 +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
6.516 +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
6.517 +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
6.518 +
6.519 +if (!Function.prototype['bind']) {
6.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)
6.521 + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
6.522 + Function.prototype['bind'] = function (object) {
6.523 + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
6.524 + return function () {
6.525 + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
6.526 + };
6.527 + };
6.528 +}
6.529 +
6.530 +ko.utils.domData = new (function () {
6.531 + var uniqueId = 0;
6.532 + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
6.533 + var dataStore = {};
6.534 + return {
6.535 + get: function (node, key) {
6.536 + var allDataForNode = ko.utils.domData.getAll(node, false);
6.537 + return allDataForNode === undefined ? undefined : allDataForNode[key];
6.538 + },
6.539 + set: function (node, key, value) {
6.540 + if (value === undefined) {
6.541 + // Make sure we don't actually create a new domData key if we are actually deleting a value
6.542 + if (ko.utils.domData.getAll(node, false) === undefined)
6.543 + return;
6.544 + }
6.545 + var allDataForNode = ko.utils.domData.getAll(node, true);
6.546 + allDataForNode[key] = value;
6.547 + },
6.548 + getAll: function (node, createIfNotFound) {
6.549 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
6.550 + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
6.551 + if (!hasExistingDataStore) {
6.552 + if (!createIfNotFound)
6.553 + return undefined;
6.554 + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
6.555 + dataStore[dataStoreKey] = {};
6.556 + }
6.557 + return dataStore[dataStoreKey];
6.558 + },
6.559 + clear: function (node) {
6.560 + var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
6.561 + if (dataStoreKey) {
6.562 + delete dataStore[dataStoreKey];
6.563 + node[dataStoreKeyExpandoPropertyName] = null;
6.564 + return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
6.565 + }
6.566 + return false;
6.567 + }
6.568 + }
6.569 +})();
6.570 +
6.571 +ko.exportSymbol('utils.domData', ko.utils.domData);
6.572 +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
6.573 +
6.574 +ko.utils.domNodeDisposal = new (function () {
6.575 + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime();
6.576 + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
6.577 + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
6.578 +
6.579 + function getDisposeCallbacksCollection(node, createIfNotFound) {
6.580 + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
6.581 + if ((allDisposeCallbacks === undefined) && createIfNotFound) {
6.582 + allDisposeCallbacks = [];
6.583 + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
6.584 + }
6.585 + return allDisposeCallbacks;
6.586 + }
6.587 + function destroyCallbacksCollection(node) {
6.588 + ko.utils.domData.set(node, domDataKey, undefined);
6.589 + }
6.590 +
6.591 + function cleanSingleNode(node) {
6.592 + // Run all the dispose callbacks
6.593 + var callbacks = getDisposeCallbacksCollection(node, false);
6.594 + if (callbacks) {
6.595 + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
6.596 + for (var i = 0; i < callbacks.length; i++)
6.597 + callbacks[i](node);
6.598 + }
6.599 +
6.600 + // Also erase the DOM data
6.601 + ko.utils.domData.clear(node);
6.602 +
6.603 + // Special support for jQuery here because it's so commonly used.
6.604 + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
6.605 + // so notify it to tear down any resources associated with the node & descendants here.
6.606 + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function"))
6.607 + jQuery['cleanData']([node]);
6.608 +
6.609 + // Also clear any immediate-child comment nodes, as these wouldn't have been found by
6.610 + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
6.611 + if (cleanableNodeTypesWithDescendants[node.nodeType])
6.612 + cleanImmediateCommentTypeChildren(node);
6.613 + }
6.614 +
6.615 + function cleanImmediateCommentTypeChildren(nodeWithChildren) {
6.616 + var child, nextChild = nodeWithChildren.firstChild;
6.617 + while (child = nextChild) {
6.618 + nextChild = child.nextSibling;
6.619 + if (child.nodeType === 8)
6.620 + cleanSingleNode(child);
6.621 + }
6.622 + }
6.623 +
6.624 + return {
6.625 + addDisposeCallback : function(node, callback) {
6.626 + if (typeof callback != "function")
6.627 + throw new Error("Callback must be a function");
6.628 + getDisposeCallbacksCollection(node, true).push(callback);
6.629 + },
6.630 +
6.631 + removeDisposeCallback : function(node, callback) {
6.632 + var callbacksCollection = getDisposeCallbacksCollection(node, false);
6.633 + if (callbacksCollection) {
6.634 + ko.utils.arrayRemoveItem(callbacksCollection, callback);
6.635 + if (callbacksCollection.length == 0)
6.636 + destroyCallbacksCollection(node);
6.637 + }
6.638 + },
6.639 +
6.640 + cleanNode : function(node) {
6.641 + // First clean this node, where applicable
6.642 + if (cleanableNodeTypes[node.nodeType]) {
6.643 + cleanSingleNode(node);
6.644 +
6.645 + // ... then its descendants, where applicable
6.646 + if (cleanableNodeTypesWithDescendants[node.nodeType]) {
6.647 + // Clone the descendants list in case it changes during iteration
6.648 + var descendants = [];
6.649 + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
6.650 + for (var i = 0, j = descendants.length; i < j; i++)
6.651 + cleanSingleNode(descendants[i]);
6.652 + }
6.653 + }
6.654 + return node;
6.655 + },
6.656 +
6.657 + removeNode : function(node) {
6.658 + ko.cleanNode(node);
6.659 + if (node.parentNode)
6.660 + node.parentNode.removeChild(node);
6.661 + }
6.662 + }
6.663 +})();
6.664 +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
6.665 +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
6.666 +ko.exportSymbol('cleanNode', ko.cleanNode);
6.667 +ko.exportSymbol('removeNode', ko.removeNode);
6.668 +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
6.669 +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
6.670 +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
6.671 +(function () {
6.672 + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
6.673 +
6.674 + function simpleHtmlParse(html) {
6.675 + // Based on jQuery's "clean" function, but only accounting for table-related elements.
6.676 + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
6.677 +
6.678 + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
6.679 + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
6.680 + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
6.681 + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
6.682 +
6.683 + // Trim whitespace, otherwise indexOf won't work as expected
6.684 + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
6.685 +
6.686 + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
6.687 + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
6.688 + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
6.689 + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
6.690 + /* anything else */ [0, "", ""];
6.691 +
6.692 + // Go to html and back, then peel off extra wrappers
6.693 + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
6.694 + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
6.695 + if (typeof window['innerShiv'] == "function") {
6.696 + div.appendChild(window['innerShiv'](markup));
6.697 + } else {
6.698 + div.innerHTML = markup;
6.699 + }
6.700 +
6.701 + // Move to the right depth
6.702 + while (wrap[0]--)
6.703 + div = div.lastChild;
6.704 +
6.705 + return ko.utils.makeArray(div.lastChild.childNodes);
6.706 + }
6.707 +
6.708 + function jQueryHtmlParse(html) {
6.709 + // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
6.710 + if (jQuery['parseHTML']) {
6.711 + return jQuery['parseHTML'](html);
6.712 + } else {
6.713 + // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
6.714 + var elems = jQuery['clean']([html]);
6.715 +
6.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.
6.717 + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
6.718 + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
6.719 + if (elems && elems[0]) {
6.720 + // Find the top-most parent element that's a direct child of a document fragment
6.721 + var elem = elems[0];
6.722 + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
6.723 + elem = elem.parentNode;
6.724 + // ... then detach it
6.725 + if (elem.parentNode)
6.726 + elem.parentNode.removeChild(elem);
6.727 + }
6.728 +
6.729 + return elems;
6.730 + }
6.731 + }
6.732 +
6.733 + ko.utils.parseHtmlFragment = function(html) {
6.734 + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
6.735 + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
6.736 + };
6.737 +
6.738 + ko.utils.setHtml = function(node, html) {
6.739 + ko.utils.emptyDomNode(node);
6.740 +
6.741 + // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
6.742 + html = ko.utils.unwrapObservable(html);
6.743 +
6.744 + if ((html !== null) && (html !== undefined)) {
6.745 + if (typeof html != 'string')
6.746 + html = html.toString();
6.747 +
6.748 + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
6.749 + // for example <tr> elements which are not normally allowed to exist on their own.
6.750 + // If you've referenced jQuery we'll use that rather than duplicating its code.
6.751 + if (typeof jQuery != 'undefined') {
6.752 + jQuery(node)['html'](html);
6.753 + } else {
6.754 + // ... otherwise, use KO's own parsing logic.
6.755 + var parsedNodes = ko.utils.parseHtmlFragment(html);
6.756 + for (var i = 0; i < parsedNodes.length; i++)
6.757 + node.appendChild(parsedNodes[i]);
6.758 + }
6.759 + }
6.760 + };
6.761 +})();
6.762 +
6.763 +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
6.764 +ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
6.765 +
6.766 +ko.memoization = (function () {
6.767 + var memos = {};
6.768 +
6.769 + function randomMax8HexChars() {
6.770 + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
6.771 + }
6.772 + function generateRandomId() {
6.773 + return randomMax8HexChars() + randomMax8HexChars();
6.774 + }
6.775 + function findMemoNodes(rootNode, appendToArray) {
6.776 + if (!rootNode)
6.777 + return;
6.778 + if (rootNode.nodeType == 8) {
6.779 + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
6.780 + if (memoId != null)
6.781 + appendToArray.push({ domNode: rootNode, memoId: memoId });
6.782 + } else if (rootNode.nodeType == 1) {
6.783 + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
6.784 + findMemoNodes(childNodes[i], appendToArray);
6.785 + }
6.786 + }
6.787 +
6.788 + return {
6.789 + memoize: function (callback) {
6.790 + if (typeof callback != "function")
6.791 + throw new Error("You can only pass a function to ko.memoization.memoize()");
6.792 + var memoId = generateRandomId();
6.793 + memos[memoId] = callback;
6.794 + return "<!--[ko_memo:" + memoId + "]-->";
6.795 + },
6.796 +
6.797 + unmemoize: function (memoId, callbackParams) {
6.798 + var callback = memos[memoId];
6.799 + if (callback === undefined)
6.800 + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
6.801 + try {
6.802 + callback.apply(null, callbackParams || []);
6.803 + return true;
6.804 + }
6.805 + finally { delete memos[memoId]; }
6.806 + },
6.807 +
6.808 + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
6.809 + var memos = [];
6.810 + findMemoNodes(domNode, memos);
6.811 + for (var i = 0, j = memos.length; i < j; i++) {
6.812 + var node = memos[i].domNode;
6.813 + var combinedParams = [node];
6.814 + if (extraCallbackParamsArray)
6.815 + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
6.816 + ko.memoization.unmemoize(memos[i].memoId, combinedParams);
6.817 + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
6.818 + if (node.parentNode)
6.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)
6.820 + }
6.821 + },
6.822 +
6.823 + parseMemoText: function (memoText) {
6.824 + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
6.825 + return match ? match[1] : null;
6.826 + }
6.827 + };
6.828 +})();
6.829 +
6.830 +ko.exportSymbol('memoization', ko.memoization);
6.831 +ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
6.832 +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
6.833 +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
6.834 +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
6.835 +ko.extenders = {
6.836 + 'throttle': function(target, timeout) {
6.837 + // Throttling means two things:
6.838 +
6.839 + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
6.840 + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
6.841 + target['throttleEvaluation'] = timeout;
6.842 +
6.843 + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
6.844 + // so the target cannot change value synchronously or faster than a certain rate
6.845 + var writeTimeoutInstance = null;
6.846 + return ko.dependentObservable({
6.847 + 'read': target,
6.848 + 'write': function(value) {
6.849 + clearTimeout(writeTimeoutInstance);
6.850 + writeTimeoutInstance = setTimeout(function() {
6.851 + target(value);
6.852 + }, timeout);
6.853 + }
6.854 + });
6.855 + },
6.856 +
6.857 + 'notify': function(target, notifyWhen) {
6.858 + target["equalityComparer"] = notifyWhen == "always"
6.859 + ? function() { return false } // Treat all values as not equal
6.860 + : ko.observable["fn"]["equalityComparer"];
6.861 + return target;
6.862 + }
6.863 +};
6.864 +
6.865 +function applyExtenders(requestedExtenders) {
6.866 + var target = this;
6.867 + if (requestedExtenders) {
6.868 + for (var key in requestedExtenders) {
6.869 + var extenderHandler = ko.extenders[key];
6.870 + if (typeof extenderHandler == 'function') {
6.871 + target = extenderHandler(target, requestedExtenders[key]);
6.872 + }
6.873 + }
6.874 + }
6.875 + return target;
6.876 +}
6.877 +
6.878 +ko.exportSymbol('extenders', ko.extenders);
6.879 +
6.880 +ko.subscription = function (target, callback, disposeCallback) {
6.881 + this.target = target;
6.882 + this.callback = callback;
6.883 + this.disposeCallback = disposeCallback;
6.884 + ko.exportProperty(this, 'dispose', this.dispose);
6.885 +};
6.886 +ko.subscription.prototype.dispose = function () {
6.887 + this.isDisposed = true;
6.888 + this.disposeCallback();
6.889 +};
6.890 +
6.891 +ko.subscribable = function () {
6.892 + this._subscriptions = {};
6.893 +
6.894 + ko.utils.extend(this, ko.subscribable['fn']);
6.895 + ko.exportProperty(this, 'subscribe', this.subscribe);
6.896 + ko.exportProperty(this, 'extend', this.extend);
6.897 + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount);
6.898 +}
6.899 +
6.900 +var defaultEvent = "change";
6.901 +
6.902 +ko.subscribable['fn'] = {
6.903 + subscribe: function (callback, callbackTarget, event) {
6.904 + event = event || defaultEvent;
6.905 + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
6.906 +
6.907 + var subscription = new ko.subscription(this, boundCallback, function () {
6.908 + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription);
6.909 + }.bind(this));
6.910 +
6.911 + if (!this._subscriptions[event])
6.912 + this._subscriptions[event] = [];
6.913 + this._subscriptions[event].push(subscription);
6.914 + return subscription;
6.915 + },
6.916 +
6.917 + "notifySubscribers": function (valueToNotify, event) {
6.918 + event = event || defaultEvent;
6.919 + if (this._subscriptions[event]) {
6.920 + ko.dependencyDetection.ignore(function() {
6.921 + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
6.922 + // In case a subscription was disposed during the arrayForEach cycle, check
6.923 + // for isDisposed on each subscription before invoking its callback
6.924 + if (subscription && (subscription.isDisposed !== true))
6.925 + subscription.callback(valueToNotify);
6.926 + });
6.927 + }, this);
6.928 + }
6.929 + },
6.930 +
6.931 + getSubscriptionsCount: function () {
6.932 + var total = 0;
6.933 + for (var eventName in this._subscriptions) {
6.934 + if (this._subscriptions.hasOwnProperty(eventName))
6.935 + total += this._subscriptions[eventName].length;
6.936 + }
6.937 + return total;
6.938 + },
6.939 +
6.940 + extend: applyExtenders
6.941 +};
6.942 +
6.943 +
6.944 +ko.isSubscribable = function (instance) {
6.945 + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
6.946 +};
6.947 +
6.948 +ko.exportSymbol('subscribable', ko.subscribable);
6.949 +ko.exportSymbol('isSubscribable', ko.isSubscribable);
6.950 +
6.951 +ko.dependencyDetection = (function () {
6.952 + var _frames = [];
6.953 +
6.954 + return {
6.955 + begin: function (callback) {
6.956 + _frames.push({ callback: callback, distinctDependencies:[] });
6.957 + },
6.958 +
6.959 + end: function () {
6.960 + _frames.pop();
6.961 + },
6.962 +
6.963 + registerDependency: function (subscribable) {
6.964 + if (!ko.isSubscribable(subscribable))
6.965 + throw new Error("Only subscribable things can act as dependencies");
6.966 + if (_frames.length > 0) {
6.967 + var topFrame = _frames[_frames.length - 1];
6.968 + if (!topFrame || ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0)
6.969 + return;
6.970 + topFrame.distinctDependencies.push(subscribable);
6.971 + topFrame.callback(subscribable);
6.972 + }
6.973 + },
6.974 +
6.975 + ignore: function(callback, callbackTarget, callbackArgs) {
6.976 + try {
6.977 + _frames.push(null);
6.978 + return callback.apply(callbackTarget, callbackArgs || []);
6.979 + } finally {
6.980 + _frames.pop();
6.981 + }
6.982 + }
6.983 + };
6.984 +})();
6.985 +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true };
6.986 +
6.987 +ko.observable = function (initialValue) {
6.988 + var _latestValue = initialValue;
6.989 +
6.990 + function observable() {
6.991 + if (arguments.length > 0) {
6.992 + // Write
6.993 +
6.994 + // Ignore writes if the value hasn't changed
6.995 + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
6.996 + observable.valueWillMutate();
6.997 + _latestValue = arguments[0];
6.998 + if (DEBUG) observable._latestValue = _latestValue;
6.999 + observable.valueHasMutated();
6.1000 + }
6.1001 + return this; // Permits chained assignments
6.1002 + }
6.1003 + else {
6.1004 + // Read
6.1005 + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
6.1006 + return _latestValue;
6.1007 + }
6.1008 + }
6.1009 + if (DEBUG) observable._latestValue = _latestValue;
6.1010 + ko.subscribable.call(observable);
6.1011 + observable.peek = function() { return _latestValue };
6.1012 + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
6.1013 + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
6.1014 + ko.utils.extend(observable, ko.observable['fn']);
6.1015 +
6.1016 + ko.exportProperty(observable, 'peek', observable.peek);
6.1017 + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
6.1018 + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
6.1019 +
6.1020 + return observable;
6.1021 +}
6.1022 +
6.1023 +ko.observable['fn'] = {
6.1024 + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) {
6.1025 + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
6.1026 + return oldValueIsPrimitive ? (a === b) : false;
6.1027 + }
6.1028 +};
6.1029 +
6.1030 +var protoProperty = ko.observable.protoProperty = "__ko_proto__";
6.1031 +ko.observable['fn'][protoProperty] = ko.observable;
6.1032 +
6.1033 +ko.hasPrototype = function(instance, prototype) {
6.1034 + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
6.1035 + if (instance[protoProperty] === prototype) return true;
6.1036 + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
6.1037 +};
6.1038 +
6.1039 +ko.isObservable = function (instance) {
6.1040 + return ko.hasPrototype(instance, ko.observable);
6.1041 +}
6.1042 +ko.isWriteableObservable = function (instance) {
6.1043 + // Observable
6.1044 + if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
6.1045 + return true;
6.1046 + // Writeable dependent observable
6.1047 + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
6.1048 + return true;
6.1049 + // Anything else
6.1050 + return false;
6.1051 +}
6.1052 +
6.1053 +
6.1054 +ko.exportSymbol('observable', ko.observable);
6.1055 +ko.exportSymbol('isObservable', ko.isObservable);
6.1056 +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
6.1057 +ko.observableArray = function (initialValues) {
6.1058 + if (arguments.length == 0) {
6.1059 + // Zero-parameter constructor initializes to empty array
6.1060 + initialValues = [];
6.1061 + }
6.1062 + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))
6.1063 + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
6.1064 +
6.1065 + var result = ko.observable(initialValues);
6.1066 + ko.utils.extend(result, ko.observableArray['fn']);
6.1067 + return result;
6.1068 +}
6.1069 +
6.1070 +ko.observableArray['fn'] = {
6.1071 + 'remove': function (valueOrPredicate) {
6.1072 + var underlyingArray = this.peek();
6.1073 + var removedValues = [];
6.1074 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
6.1075 + for (var i = 0; i < underlyingArray.length; i++) {
6.1076 + var value = underlyingArray[i];
6.1077 + if (predicate(value)) {
6.1078 + if (removedValues.length === 0) {
6.1079 + this.valueWillMutate();
6.1080 + }
6.1081 + removedValues.push(value);
6.1082 + underlyingArray.splice(i, 1);
6.1083 + i--;
6.1084 + }
6.1085 + }
6.1086 + if (removedValues.length) {
6.1087 + this.valueHasMutated();
6.1088 + }
6.1089 + return removedValues;
6.1090 + },
6.1091 +
6.1092 + 'removeAll': function (arrayOfValues) {
6.1093 + // If you passed zero args, we remove everything
6.1094 + if (arrayOfValues === undefined) {
6.1095 + var underlyingArray = this.peek();
6.1096 + var allValues = underlyingArray.slice(0);
6.1097 + this.valueWillMutate();
6.1098 + underlyingArray.splice(0, underlyingArray.length);
6.1099 + this.valueHasMutated();
6.1100 + return allValues;
6.1101 + }
6.1102 + // If you passed an arg, we interpret it as an array of entries to remove
6.1103 + if (!arrayOfValues)
6.1104 + return [];
6.1105 + return this['remove'](function (value) {
6.1106 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
6.1107 + });
6.1108 + },
6.1109 +
6.1110 + 'destroy': function (valueOrPredicate) {
6.1111 + var underlyingArray = this.peek();
6.1112 + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
6.1113 + this.valueWillMutate();
6.1114 + for (var i = underlyingArray.length - 1; i >= 0; i--) {
6.1115 + var value = underlyingArray[i];
6.1116 + if (predicate(value))
6.1117 + underlyingArray[i]["_destroy"] = true;
6.1118 + }
6.1119 + this.valueHasMutated();
6.1120 + },
6.1121 +
6.1122 + 'destroyAll': function (arrayOfValues) {
6.1123 + // If you passed zero args, we destroy everything
6.1124 + if (arrayOfValues === undefined)
6.1125 + return this['destroy'](function() { return true });
6.1126 +
6.1127 + // If you passed an arg, we interpret it as an array of entries to destroy
6.1128 + if (!arrayOfValues)
6.1129 + return [];
6.1130 + return this['destroy'](function (value) {
6.1131 + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
6.1132 + });
6.1133 + },
6.1134 +
6.1135 + 'indexOf': function (item) {
6.1136 + var underlyingArray = this();
6.1137 + return ko.utils.arrayIndexOf(underlyingArray, item);
6.1138 + },
6.1139 +
6.1140 + 'replace': function(oldItem, newItem) {
6.1141 + var index = this['indexOf'](oldItem);
6.1142 + if (index >= 0) {
6.1143 + this.valueWillMutate();
6.1144 + this.peek()[index] = newItem;
6.1145 + this.valueHasMutated();
6.1146 + }
6.1147 + }
6.1148 +}
6.1149 +
6.1150 +// Populate ko.observableArray.fn with read/write functions from native arrays
6.1151 +// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
6.1152 +// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
6.1153 +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
6.1154 + ko.observableArray['fn'][methodName] = function () {
6.1155 + // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
6.1156 + // (for consistency with mutating regular observables)
6.1157 + var underlyingArray = this.peek();
6.1158 + this.valueWillMutate();
6.1159 + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
6.1160 + this.valueHasMutated();
6.1161 + return methodCallResult;
6.1162 + };
6.1163 +});
6.1164 +
6.1165 +// Populate ko.observableArray.fn with read-only functions from native arrays
6.1166 +ko.utils.arrayForEach(["slice"], function (methodName) {
6.1167 + ko.observableArray['fn'][methodName] = function () {
6.1168 + var underlyingArray = this();
6.1169 + return underlyingArray[methodName].apply(underlyingArray, arguments);
6.1170 + };
6.1171 +});
6.1172 +
6.1173 +ko.exportSymbol('observableArray', ko.observableArray);
6.1174 +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
6.1175 + var _latestValue,
6.1176 + _hasBeenEvaluated = false,
6.1177 + _isBeingEvaluated = false,
6.1178 + readFunction = evaluatorFunctionOrOptions;
6.1179 +
6.1180 + if (readFunction && typeof readFunction == "object") {
6.1181 + // Single-parameter syntax - everything is on this "options" param
6.1182 + options = readFunction;
6.1183 + readFunction = options["read"];
6.1184 + } else {
6.1185 + // Multi-parameter syntax - construct the options according to the params passed
6.1186 + options = options || {};
6.1187 + if (!readFunction)
6.1188 + readFunction = options["read"];
6.1189 + }
6.1190 + if (typeof readFunction != "function")
6.1191 + throw new Error("Pass a function that returns the value of the ko.computed");
6.1192 +
6.1193 + function addSubscriptionToDependency(subscribable) {
6.1194 + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync));
6.1195 + }
6.1196 +
6.1197 + function disposeAllSubscriptionsToDependencies() {
6.1198 + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) {
6.1199 + subscription.dispose();
6.1200 + });
6.1201 + _subscriptionsToDependencies = [];
6.1202 + }
6.1203 +
6.1204 + function evaluatePossiblyAsync() {
6.1205 + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
6.1206 + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
6.1207 + clearTimeout(evaluationTimeoutInstance);
6.1208 + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
6.1209 + } else
6.1210 + evaluateImmediate();
6.1211 + }
6.1212 +
6.1213 + function evaluateImmediate() {
6.1214 + if (_isBeingEvaluated) {
6.1215 + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
6.1216 + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
6.1217 + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
6.1218 + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
6.1219 + return;
6.1220 + }
6.1221 +
6.1222 + // Don't dispose on first evaluation, because the "disposeWhen" callback might
6.1223 + // e.g., dispose when the associated DOM element isn't in the doc, and it's not
6.1224 + // going to be in the doc until *after* the first evaluation
6.1225 + if (_hasBeenEvaluated && disposeWhen()) {
6.1226 + dispose();
6.1227 + return;
6.1228 + }
6.1229 +
6.1230 + _isBeingEvaluated = true;
6.1231 + try {
6.1232 + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
6.1233 + // Then, during evaluation, we cross off any that are in fact still being used.
6.1234 + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;});
6.1235 +
6.1236 + ko.dependencyDetection.begin(function(subscribable) {
6.1237 + var inOld;
6.1238 + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0)
6.1239 + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used
6.1240 + else
6.1241 + addSubscriptionToDependency(subscribable); // Brand new subscription - add it
6.1242 + });
6.1243 +
6.1244 + var newValue = readFunction.call(evaluatorFunctionTarget);
6.1245 +
6.1246 + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
6.1247 + for (var i = disposalCandidates.length - 1; i >= 0; i--) {
6.1248 + if (disposalCandidates[i])
6.1249 + _subscriptionsToDependencies.splice(i, 1)[0].dispose();
6.1250 + }
6.1251 + _hasBeenEvaluated = true;
6.1252 +
6.1253 + dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
6.1254 + _latestValue = newValue;
6.1255 + if (DEBUG) dependentObservable._latestValue = _latestValue;
6.1256 + } finally {
6.1257 + ko.dependencyDetection.end();
6.1258 + }
6.1259 +
6.1260 + dependentObservable["notifySubscribers"](_latestValue);
6.1261 + _isBeingEvaluated = false;
6.1262 + if (!_subscriptionsToDependencies.length)
6.1263 + dispose();
6.1264 + }
6.1265 +
6.1266 + function dependentObservable() {
6.1267 + if (arguments.length > 0) {
6.1268 + if (typeof writeFunction === "function") {
6.1269 + // Writing a value
6.1270 + writeFunction.apply(evaluatorFunctionTarget, arguments);
6.1271 + } else {
6.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.");
6.1273 + }
6.1274 + return this; // Permits chained assignments
6.1275 + } else {
6.1276 + // Reading the value
6.1277 + if (!_hasBeenEvaluated)
6.1278 + evaluateImmediate();
6.1279 + ko.dependencyDetection.registerDependency(dependentObservable);
6.1280 + return _latestValue;
6.1281 + }
6.1282 + }
6.1283 +
6.1284 + function peek() {
6.1285 + if (!_hasBeenEvaluated)
6.1286 + evaluateImmediate();
6.1287 + return _latestValue;
6.1288 + }
6.1289 +
6.1290 + function isActive() {
6.1291 + return !_hasBeenEvaluated || _subscriptionsToDependencies.length > 0;
6.1292 + }
6.1293 +
6.1294 + // By here, "options" is always non-null
6.1295 + var writeFunction = options["write"],
6.1296 + disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
6.1297 + disposeWhen = options["disposeWhen"] || options.disposeWhen || function() { return false; },
6.1298 + dispose = disposeAllSubscriptionsToDependencies,
6.1299 + _subscriptionsToDependencies = [],
6.1300 + evaluationTimeoutInstance = null;
6.1301 +
6.1302 + if (!evaluatorFunctionTarget)
6.1303 + evaluatorFunctionTarget = options["owner"];
6.1304 +
6.1305 + dependentObservable.peek = peek;
6.1306 + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; };
6.1307 + dependentObservable.hasWriteFunction = typeof options["write"] === "function";
6.1308 + dependentObservable.dispose = function () { dispose(); };
6.1309 + dependentObservable.isActive = isActive;
6.1310 + dependentObservable.valueHasMutated = function() {
6.1311 + _hasBeenEvaluated = false;
6.1312 + evaluateImmediate();
6.1313 + };
6.1314 +
6.1315 + ko.subscribable.call(dependentObservable);
6.1316 + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']);
6.1317 +
6.1318 + ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
6.1319 + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
6.1320 + ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
6.1321 + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
6.1322 +
6.1323 + // Evaluate, unless deferEvaluation is true
6.1324 + if (options['deferEvaluation'] !== true)
6.1325 + evaluateImmediate();
6.1326 +
6.1327 + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values.
6.1328 + // But skip if isActive is false (there will never be any dependencies to dispose).
6.1329 + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(),
6.1330 + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.)
6.1331 + if (disposeWhenNodeIsRemoved && isActive()) {
6.1332 + dispose = function() {
6.1333 + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee);
6.1334 + disposeAllSubscriptionsToDependencies();
6.1335 + };
6.1336 + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
6.1337 + var existingDisposeWhenFunction = disposeWhen;
6.1338 + disposeWhen = function () {
6.1339 + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction();
6.1340 + }
6.1341 + }
6.1342 +
6.1343 + return dependentObservable;
6.1344 +};
6.1345 +
6.1346 +ko.isComputed = function(instance) {
6.1347 + return ko.hasPrototype(instance, ko.dependentObservable);
6.1348 +};
6.1349 +
6.1350 +var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
6.1351 +ko.dependentObservable[protoProp] = ko.observable;
6.1352 +
6.1353 +ko.dependentObservable['fn'] = {};
6.1354 +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
6.1355 +
6.1356 +ko.exportSymbol('dependentObservable', ko.dependentObservable);
6.1357 +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
6.1358 +ko.exportSymbol('isComputed', ko.isComputed);
6.1359 +
6.1360 +(function() {
6.1361 + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
6.1362 +
6.1363 + ko.toJS = function(rootObject) {
6.1364 + if (arguments.length == 0)
6.1365 + throw new Error("When calling ko.toJS, pass the object you want to convert.");
6.1366 +
6.1367 + // We just unwrap everything at every level in the object graph
6.1368 + return mapJsObjectGraph(rootObject, function(valueToMap) {
6.1369 + // Loop because an observable's value might in turn be another observable wrapper
6.1370 + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
6.1371 + valueToMap = valueToMap();
6.1372 + return valueToMap;
6.1373 + });
6.1374 + };
6.1375 +
6.1376 + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
6.1377 + var plainJavaScriptObject = ko.toJS(rootObject);
6.1378 + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
6.1379 + };
6.1380 +
6.1381 + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
6.1382 + visitedObjects = visitedObjects || new objectLookup();
6.1383 +
6.1384 + rootObject = mapInputCallback(rootObject);
6.1385 + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date));
6.1386 + if (!canHaveProperties)
6.1387 + return rootObject;
6.1388 +
6.1389 + var outputProperties = rootObject instanceof Array ? [] : {};
6.1390 + visitedObjects.save(rootObject, outputProperties);
6.1391 +
6.1392 + visitPropertiesOrArrayEntries(rootObject, function(indexer) {
6.1393 + var propertyValue = mapInputCallback(rootObject[indexer]);
6.1394 +
6.1395 + switch (typeof propertyValue) {
6.1396 + case "boolean":
6.1397 + case "number":
6.1398 + case "string":
6.1399 + case "function":
6.1400 + outputProperties[indexer] = propertyValue;
6.1401 + break;
6.1402 + case "object":
6.1403 + case "undefined":
6.1404 + var previouslyMappedValue = visitedObjects.get(propertyValue);
6.1405 + outputProperties[indexer] = (previouslyMappedValue !== undefined)
6.1406 + ? previouslyMappedValue
6.1407 + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
6.1408 + break;
6.1409 + }
6.1410 + });
6.1411 +
6.1412 + return outputProperties;
6.1413 + }
6.1414 +
6.1415 + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
6.1416 + if (rootObject instanceof Array) {
6.1417 + for (var i = 0; i < rootObject.length; i++)
6.1418 + visitorCallback(i);
6.1419 +
6.1420 + // For arrays, also respect toJSON property for custom mappings (fixes #278)
6.1421 + if (typeof rootObject['toJSON'] == 'function')
6.1422 + visitorCallback('toJSON');
6.1423 + } else {
6.1424 + for (var propertyName in rootObject)
6.1425 + visitorCallback(propertyName);
6.1426 + }
6.1427 + };
6.1428 +
6.1429 + function objectLookup() {
6.1430 + var keys = [];
6.1431 + var values = [];
6.1432 + this.save = function(key, value) {
6.1433 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
6.1434 + if (existingIndex >= 0)
6.1435 + values[existingIndex] = value;
6.1436 + else {
6.1437 + keys.push(key);
6.1438 + values.push(value);
6.1439 + }
6.1440 + };
6.1441 + this.get = function(key) {
6.1442 + var existingIndex = ko.utils.arrayIndexOf(keys, key);
6.1443 + return (existingIndex >= 0) ? values[existingIndex] : undefined;
6.1444 + };
6.1445 + };
6.1446 +})();
6.1447 +
6.1448 +ko.exportSymbol('toJS', ko.toJS);
6.1449 +ko.exportSymbol('toJSON', ko.toJSON);
6.1450 +(function () {
6.1451 + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
6.1452 +
6.1453 + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
6.1454 + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
6.1455 + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
6.1456 + ko.selectExtensions = {
6.1457 + readValue : function(element) {
6.1458 + switch (ko.utils.tagNameLower(element)) {
6.1459 + case 'option':
6.1460 + if (element[hasDomDataExpandoProperty] === true)
6.1461 + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
6.1462 + return ko.utils.ieVersion <= 7
6.1463 + ? (element.getAttributeNode('value').specified ? element.value : element.text)
6.1464 + : element.value;
6.1465 + case 'select':
6.1466 + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
6.1467 + default:
6.1468 + return element.value;
6.1469 + }
6.1470 + },
6.1471 +
6.1472 + writeValue: function(element, value) {
6.1473 + switch (ko.utils.tagNameLower(element)) {
6.1474 + case 'option':
6.1475 + switch(typeof value) {
6.1476 + case "string":
6.1477 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
6.1478 + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
6.1479 + delete element[hasDomDataExpandoProperty];
6.1480 + }
6.1481 + element.value = value;
6.1482 + break;
6.1483 + default:
6.1484 + // Store arbitrary object using DomData
6.1485 + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
6.1486 + element[hasDomDataExpandoProperty] = true;
6.1487 +
6.1488 + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
6.1489 + element.value = typeof value === "number" ? value : "";
6.1490 + break;
6.1491 + }
6.1492 + break;
6.1493 + case 'select':
6.1494 + for (var i = element.options.length - 1; i >= 0; i--) {
6.1495 + if (ko.selectExtensions.readValue(element.options[i]) == value) {
6.1496 + element.selectedIndex = i;
6.1497 + break;
6.1498 + }
6.1499 + }
6.1500 + break;
6.1501 + default:
6.1502 + if ((value === null) || (value === undefined))
6.1503 + value = "";
6.1504 + element.value = value;
6.1505 + break;
6.1506 + }
6.1507 + }
6.1508 + };
6.1509 +})();
6.1510 +
6.1511 +ko.exportSymbol('selectExtensions', ko.selectExtensions);
6.1512 +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
6.1513 +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
6.1514 +ko.expressionRewriting = (function () {
6.1515 + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g;
6.1516 + var javaScriptReservedWords = ["true", "false"];
6.1517 +
6.1518 + // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
6.1519 + // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
6.1520 + var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
6.1521 +
6.1522 + function restoreTokens(string, tokens) {
6.1523 + var prevValue = null;
6.1524 + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested)
6.1525 + prevValue = string;
6.1526 + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) {
6.1527 + return tokens[tokenIndex];
6.1528 + });
6.1529 + }
6.1530 + return string;
6.1531 + }
6.1532 +
6.1533 + function getWriteableValue(expression) {
6.1534 + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0)
6.1535 + return false;
6.1536 + var match = expression.match(javaScriptAssignmentTarget);
6.1537 + return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
6.1538 + }
6.1539 +
6.1540 + function ensureQuoted(key) {
6.1541 + var trimmedKey = ko.utils.stringTrim(key);
6.1542 + switch (trimmedKey.length && trimmedKey.charAt(0)) {
6.1543 + case "'":
6.1544 + case '"':
6.1545 + return key;
6.1546 + default:
6.1547 + return "'" + trimmedKey + "'";
6.1548 + }
6.1549 + }
6.1550 +
6.1551 + return {
6.1552 + bindingRewriteValidators: [],
6.1553 +
6.1554 + parseObjectLiteral: function(objectLiteralString) {
6.1555 + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser
6.1556 + // that is sufficient just to split an object literal string into a set of top-level key-value pairs
6.1557 +
6.1558 + var str = ko.utils.stringTrim(objectLiteralString);
6.1559 + if (str.length < 3)
6.1560 + return [];
6.1561 + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal
6.1562 + str = str.substring(1, str.length - 1);
6.1563 +
6.1564 + // Pull out any string literals and regex literals
6.1565 + var tokens = [];
6.1566 + var tokenStart = null, tokenEndChar;
6.1567 + for (var position = 0; position < str.length; position++) {
6.1568 + var c = str.charAt(position);
6.1569 + if (tokenStart === null) {
6.1570 + switch (c) {
6.1571 + case '"':
6.1572 + case "'":
6.1573 + case "/":
6.1574 + tokenStart = position;
6.1575 + tokenEndChar = c;
6.1576 + break;
6.1577 + }
6.1578 + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) {
6.1579 + var token = str.substring(tokenStart, position + 1);
6.1580 + tokens.push(token);
6.1581 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
6.1582 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
6.1583 + position -= (token.length - replacement.length);
6.1584 + tokenStart = null;
6.1585 + }
6.1586 + }
6.1587 +
6.1588 + // Next pull out balanced paren, brace, and bracket blocks
6.1589 + tokenStart = null;
6.1590 + tokenEndChar = null;
6.1591 + var tokenDepth = 0, tokenStartChar = null;
6.1592 + for (var position = 0; position < str.length; position++) {
6.1593 + var c = str.charAt(position);
6.1594 + if (tokenStart === null) {
6.1595 + switch (c) {
6.1596 + case "{": tokenStart = position; tokenStartChar = c;
6.1597 + tokenEndChar = "}";
6.1598 + break;
6.1599 + case "(": tokenStart = position; tokenStartChar = c;
6.1600 + tokenEndChar = ")";
6.1601 + break;
6.1602 + case "[": tokenStart = position; tokenStartChar = c;
6.1603 + tokenEndChar = "]";
6.1604 + break;
6.1605 + }
6.1606 + }
6.1607 +
6.1608 + if (c === tokenStartChar)
6.1609 + tokenDepth++;
6.1610 + else if (c === tokenEndChar) {
6.1611 + tokenDepth--;
6.1612 + if (tokenDepth === 0) {
6.1613 + var token = str.substring(tokenStart, position + 1);
6.1614 + tokens.push(token);
6.1615 + var replacement = "@ko_token_" + (tokens.length - 1) + "@";
6.1616 + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1);
6.1617 + position -= (token.length - replacement.length);
6.1618 + tokenStart = null;
6.1619 + }
6.1620 + }
6.1621 + }
6.1622 +
6.1623 + // Now we can safely split on commas to get the key/value pairs
6.1624 + var result = [];
6.1625 + var keyValuePairs = str.split(",");
6.1626 + for (var i = 0, j = keyValuePairs.length; i < j; i++) {
6.1627 + var pair = keyValuePairs[i];
6.1628 + var colonPos = pair.indexOf(":");
6.1629 + if ((colonPos > 0) && (colonPos < pair.length - 1)) {
6.1630 + var key = pair.substring(0, colonPos);
6.1631 + var value = pair.substring(colonPos + 1);
6.1632 + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) });
6.1633 + } else {
6.1634 + result.push({ 'unknown': restoreTokens(pair, tokens) });
6.1635 + }
6.1636 + }
6.1637 + return result;
6.1638 + },
6.1639 +
6.1640 + preProcessBindings: function (objectLiteralStringOrKeyValueArray) {
6.1641 + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string"
6.1642 + ? ko.expressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray)
6.1643 + : objectLiteralStringOrKeyValueArray;
6.1644 + var resultStrings = [], propertyAccessorResultStrings = [];
6.1645 +
6.1646 + var keyValueEntry;
6.1647 + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) {
6.1648 + if (resultStrings.length > 0)
6.1649 + resultStrings.push(",");
6.1650 +
6.1651 + if (keyValueEntry['key']) {
6.1652 + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value'];
6.1653 + resultStrings.push(quotedKey);
6.1654 + resultStrings.push(":");
6.1655 + resultStrings.push(val);
6.1656 +
6.1657 + if (val = getWriteableValue(ko.utils.stringTrim(val))) {
6.1658 + if (propertyAccessorResultStrings.length > 0)
6.1659 + propertyAccessorResultStrings.push(", ");
6.1660 + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }");
6.1661 + }
6.1662 + } else if (keyValueEntry['unknown']) {
6.1663 + resultStrings.push(keyValueEntry['unknown']);
6.1664 + }
6.1665 + }
6.1666 +
6.1667 + var combinedResult = resultStrings.join("");
6.1668 + if (propertyAccessorResultStrings.length > 0) {
6.1669 + var allPropertyAccessors = propertyAccessorResultStrings.join("");
6.1670 + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } ";
6.1671 + }
6.1672 +
6.1673 + return combinedResult;
6.1674 + },
6.1675 +
6.1676 + keyValueArrayContainsKey: function(keyValueArray, key) {
6.1677 + for (var i = 0; i < keyValueArray.length; i++)
6.1678 + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key)
6.1679 + return true;
6.1680 + return false;
6.1681 + },
6.1682 +
6.1683 + // Internal, private KO utility for updating model properties from within bindings
6.1684 + // property: If the property being updated is (or might be) an observable, pass it here
6.1685 + // If it turns out to be a writable observable, it will be written to directly
6.1686 + // allBindingsAccessor: All bindings in the current execution context.
6.1687 + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
6.1688 + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
6.1689 + // value: The value to be written
6.1690 + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
6.1691 + // it is !== existing value on that writable observable
6.1692 + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) {
6.1693 + if (!property || !ko.isWriteableObservable(property)) {
6.1694 + var propWriters = allBindingsAccessor()['_ko_property_writers'];
6.1695 + if (propWriters && propWriters[key])
6.1696 + propWriters[key](value);
6.1697 + } else if (!checkIfDifferent || property.peek() !== value) {
6.1698 + property(value);
6.1699 + }
6.1700 + }
6.1701 + };
6.1702 +})();
6.1703 +
6.1704 +ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
6.1705 +ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
6.1706 +ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
6.1707 +ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
6.1708 +
6.1709 +// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
6.1710 +// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
6.1711 +ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
6.1712 +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);(function() {
6.1713 + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
6.1714 + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
6.1715 + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
6.1716 + // of that virtual hierarchy
6.1717 + //
6.1718 + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
6.1719 + // without having to scatter special cases all over the binding and templating code.
6.1720 +
6.1721 + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
6.1722 + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
6.1723 + // So, use node.text where available, and node.nodeValue elsewhere
6.1724 + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->";
6.1725 +
6.1726 + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*-->$/ : /^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/;
6.1727 + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
6.1728 + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
6.1729 +
6.1730 + function isStartComment(node) {
6.1731 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
6.1732 + }
6.1733 +
6.1734 + function isEndComment(node) {
6.1735 + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex);
6.1736 + }
6.1737 +
6.1738 + function getVirtualChildren(startComment, allowUnbalanced) {
6.1739 + var currentNode = startComment;
6.1740 + var depth = 1;
6.1741 + var children = [];
6.1742 + while (currentNode = currentNode.nextSibling) {
6.1743 + if (isEndComment(currentNode)) {
6.1744 + depth--;
6.1745 + if (depth === 0)
6.1746 + return children;
6.1747 + }
6.1748 +
6.1749 + children.push(currentNode);
6.1750 +
6.1751 + if (isStartComment(currentNode))
6.1752 + depth++;
6.1753 + }
6.1754 + if (!allowUnbalanced)
6.1755 + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
6.1756 + return null;
6.1757 + }
6.1758 +
6.1759 + function getMatchingEndComment(startComment, allowUnbalanced) {
6.1760 + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
6.1761 + if (allVirtualChildren) {
6.1762 + if (allVirtualChildren.length > 0)
6.1763 + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
6.1764 + return startComment.nextSibling;
6.1765 + } else
6.1766 + return null; // Must have no matching end comment, and allowUnbalanced is true
6.1767 + }
6.1768 +
6.1769 + function getUnbalancedChildTags(node) {
6.1770 + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
6.1771 + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
6.1772 + var childNode = node.firstChild, captureRemaining = null;
6.1773 + if (childNode) {
6.1774 + do {
6.1775 + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
6.1776 + captureRemaining.push(childNode);
6.1777 + else if (isStartComment(childNode)) {
6.1778 + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
6.1779 + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
6.1780 + childNode = matchingEndComment;
6.1781 + else
6.1782 + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
6.1783 + } else if (isEndComment(childNode)) {
6.1784 + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
6.1785 + }
6.1786 + } while (childNode = childNode.nextSibling);
6.1787 + }
6.1788 + return captureRemaining;
6.1789 + }
6.1790 +
6.1791 + ko.virtualElements = {
6.1792 + allowedBindings: {},
6.1793 +
6.1794 + childNodes: function(node) {
6.1795 + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
6.1796 + },
6.1797 +
6.1798 + emptyNode: function(node) {
6.1799 + if (!isStartComment(node))
6.1800 + ko.utils.emptyDomNode(node);
6.1801 + else {
6.1802 + var virtualChildren = ko.virtualElements.childNodes(node);
6.1803 + for (var i = 0, j = virtualChildren.length; i < j; i++)
6.1804 + ko.removeNode(virtualChildren[i]);
6.1805 + }
6.1806 + },
6.1807 +
6.1808 + setDomNodeChildren: function(node, childNodes) {
6.1809 + if (!isStartComment(node))
6.1810 + ko.utils.setDomNodeChildren(node, childNodes);
6.1811 + else {
6.1812 + ko.virtualElements.emptyNode(node);
6.1813 + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
6.1814 + for (var i = 0, j = childNodes.length; i < j; i++)
6.1815 + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
6.1816 + }
6.1817 + },
6.1818 +
6.1819 + prepend: function(containerNode, nodeToPrepend) {
6.1820 + if (!isStartComment(containerNode)) {
6.1821 + if (containerNode.firstChild)
6.1822 + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
6.1823 + else
6.1824 + containerNode.appendChild(nodeToPrepend);
6.1825 + } else {
6.1826 + // Start comments must always have a parent and at least one following sibling (the end comment)
6.1827 + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
6.1828 + }
6.1829 + },
6.1830 +
6.1831 + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
6.1832 + if (!insertAfterNode) {
6.1833 + ko.virtualElements.prepend(containerNode, nodeToInsert);
6.1834 + } else if (!isStartComment(containerNode)) {
6.1835 + // Insert after insertion point
6.1836 + if (insertAfterNode.nextSibling)
6.1837 + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
6.1838 + else
6.1839 + containerNode.appendChild(nodeToInsert);
6.1840 + } else {
6.1841 + // Children of start comments must always have a parent and at least one following sibling (the end comment)
6.1842 + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
6.1843 + }
6.1844 + },
6.1845 +
6.1846 + firstChild: function(node) {
6.1847 + if (!isStartComment(node))
6.1848 + return node.firstChild;
6.1849 + if (!node.nextSibling || isEndComment(node.nextSibling))
6.1850 + return null;
6.1851 + return node.nextSibling;
6.1852 + },
6.1853 +
6.1854 + nextSibling: function(node) {
6.1855 + if (isStartComment(node))
6.1856 + node = getMatchingEndComment(node);
6.1857 + if (node.nextSibling && isEndComment(node.nextSibling))
6.1858 + return null;
6.1859 + return node.nextSibling;
6.1860 + },
6.1861 +
6.1862 + virtualNodeBindingValue: function(node) {
6.1863 + var regexMatch = isStartComment(node);
6.1864 + return regexMatch ? regexMatch[1] : null;
6.1865 + },
6.1866 +
6.1867 + normaliseVirtualElementDomStructure: function(elementVerified) {
6.1868 + // Workaround for https://github.com/SteveSanderson/knockout/issues/155
6.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
6.1870 + // that are direct descendants of <ul> into the preceding <li>)
6.1871 + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
6.1872 + return;
6.1873 +
6.1874 + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
6.1875 + // must be intended to appear *after* that child, so move them there.
6.1876 + var childNode = elementVerified.firstChild;
6.1877 + if (childNode) {
6.1878 + do {
6.1879 + if (childNode.nodeType === 1) {
6.1880 + var unbalancedTags = getUnbalancedChildTags(childNode);
6.1881 + if (unbalancedTags) {
6.1882 + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
6.1883 + var nodeToInsertBefore = childNode.nextSibling;
6.1884 + for (var i = 0; i < unbalancedTags.length; i++) {
6.1885 + if (nodeToInsertBefore)
6.1886 + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
6.1887 + else
6.1888 + elementVerified.appendChild(unbalancedTags[i]);
6.1889 + }
6.1890 + }
6.1891 + }
6.1892 + } while (childNode = childNode.nextSibling);
6.1893 + }
6.1894 + }
6.1895 + };
6.1896 +})();
6.1897 +ko.exportSymbol('virtualElements', ko.virtualElements);
6.1898 +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
6.1899 +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
6.1900 +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
6.1901 +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
6.1902 +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
6.1903 +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
6.1904 +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
6.1905 +(function() {
6.1906 + var defaultBindingAttributeName = "data-bind";
6.1907 +
6.1908 + ko.bindingProvider = function() {
6.1909 + this.bindingCache = {};
6.1910 + };
6.1911 +
6.1912 + ko.utils.extend(ko.bindingProvider.prototype, {
6.1913 + 'nodeHasBindings': function(node) {
6.1914 + switch (node.nodeType) {
6.1915 + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
6.1916 + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node
6.1917 + default: return false;
6.1918 + }
6.1919 + },
6.1920 +
6.1921 + 'getBindings': function(node, bindingContext) {
6.1922 + var bindingsString = this['getBindingsString'](node, bindingContext);
6.1923 + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
6.1924 + },
6.1925 +
6.1926 + // The following function is only used internally by this default provider.
6.1927 + // It's not part of the interface definition for a general binding provider.
6.1928 + 'getBindingsString': function(node, bindingContext) {
6.1929 + switch (node.nodeType) {
6.1930 + case 1: return node.getAttribute(defaultBindingAttributeName); // Element
6.1931 + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
6.1932 + default: return null;
6.1933 + }
6.1934 + },
6.1935 +
6.1936 + // The following function is only used internally by this default provider.
6.1937 + // It's not part of the interface definition for a general binding provider.
6.1938 + 'parseBindingsString': function(bindingsString, bindingContext, node) {
6.1939 + try {
6.1940 + var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache);
6.1941 + return bindingFunction(bindingContext, node);
6.1942 + } catch (ex) {
6.1943 + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString);
6.1944 + }
6.1945 + }
6.1946 + });
6.1947 +
6.1948 + ko.bindingProvider['instance'] = new ko.bindingProvider();
6.1949 +
6.1950 + function createBindingsStringEvaluatorViaCache(bindingsString, cache) {
6.1951 + var cacheKey = bindingsString;
6.1952 + return cache[cacheKey]
6.1953 + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString));
6.1954 + }
6.1955 +
6.1956 + function createBindingsStringEvaluator(bindingsString) {
6.1957 + // Build the source for a function that evaluates "expression"
6.1958 + // For each scope variable, add an extra level of "with" nesting
6.1959 + // Example result: with(sc1) { with(sc0) { return (expression) } }
6.1960 + var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString),
6.1961 + functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
6.1962 + return new Function("$context", "$element", functionBody);
6.1963 + }
6.1964 +})();
6.1965 +
6.1966 +ko.exportSymbol('bindingProvider', ko.bindingProvider);
6.1967 +(function () {
6.1968 + ko.bindingHandlers = {};
6.1969 +
6.1970 + ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
6.1971 + if (parentBindingContext) {
6.1972 + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
6.1973 + this['$parentContext'] = parentBindingContext;
6.1974 + this['$parent'] = parentBindingContext['$data'];
6.1975 + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
6.1976 + this['$parents'].unshift(this['$parent']);
6.1977 + } else {
6.1978 + this['$parents'] = [];
6.1979 + this['$root'] = dataItem;
6.1980 + // Export 'ko' in the binding context so it will be available in bindings and templates
6.1981 + // even if 'ko' isn't exported as a global, such as when using an AMD loader.
6.1982 + // See https://github.com/SteveSanderson/knockout/issues/490
6.1983 + this['ko'] = ko;
6.1984 + }
6.1985 + this['$data'] = dataItem;
6.1986 + if (dataItemAlias)
6.1987 + this[dataItemAlias] = dataItem;
6.1988 + }
6.1989 + ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
6.1990 + return new ko.bindingContext(dataItem, this, dataItemAlias);
6.1991 + };
6.1992 + ko.bindingContext.prototype['extend'] = function(properties) {
6.1993 + var clone = ko.utils.extend(new ko.bindingContext(), this);
6.1994 + return ko.utils.extend(clone, properties);
6.1995 + };
6.1996 +
6.1997 + function validateThatBindingIsAllowedForVirtualElements(bindingName) {
6.1998 + var validator = ko.virtualElements.allowedBindings[bindingName];
6.1999 + if (!validator)
6.2000 + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
6.2001 + }
6.2002 +
6.2003 + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
6.2004 + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
6.2005 + while (currentChild = nextInQueue) {
6.2006 + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
6.2007 + nextInQueue = ko.virtualElements.nextSibling(currentChild);
6.2008 + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
6.2009 + }
6.2010 + }
6.2011 +
6.2012 + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
6.2013 + var shouldBindDescendants = true;
6.2014 +
6.2015 + // Perf optimisation: Apply bindings only if...
6.2016 + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
6.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
6.2018 + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
6.2019 + var isElement = (nodeVerified.nodeType === 1);
6.2020 + if (isElement) // Workaround IE <= 8 HTML parsing weirdness
6.2021 + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
6.2022 +
6.2023 + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
6.2024 + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
6.2025 + if (shouldApplyBindings)
6.2026 + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
6.2027 +
6.2028 + if (shouldBindDescendants) {
6.2029 + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
6.2030 + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
6.2031 + // hence bindingContextsMayDifferFromDomParentElement is false
6.2032 + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
6.2033 + // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
6.2034 + // hence bindingContextsMayDifferFromDomParentElement is true
6.2035 + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
6.2036 + }
6.2037 + }
6.2038 +
6.2039 + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
6.2040 + // Need to be sure that inits are only run once, and updates never run until all the inits have been run
6.2041 + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
6.2042 +
6.2043 + // Each time the dependentObservable is evaluated (after data changes),
6.2044 + // the binding attribute is reparsed so that it can pick out the correct
6.2045 + // model properties in the context of the changed data.
6.2046 + // DOM event callbacks need to be able to access this changed data,
6.2047 + // so we need a single parsedBindings variable (shared by all callbacks
6.2048 + // associated with this node's bindings) that all the closures can access.
6.2049 + var parsedBindings;
6.2050 + function makeValueAccessor(bindingKey) {
6.2051 + return function () { return parsedBindings[bindingKey] }
6.2052 + }
6.2053 + function parsedBindingsAccessor() {
6.2054 + return parsedBindings;
6.2055 + }
6.2056 +
6.2057 + var bindingHandlerThatControlsDescendantBindings;
6.2058 + ko.dependentObservable(
6.2059 + function () {
6.2060 + // Ensure we have a nonnull binding context to work with
6.2061 + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
6.2062 + ? viewModelOrBindingContext
6.2063 + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
6.2064 + var viewModel = bindingContextInstance['$data'];
6.2065 +
6.2066 + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
6.2067 + // we can easily recover it just by scanning up the node's ancestors in the DOM
6.2068 + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
6.2069 + if (bindingContextMayDifferFromDomParentElement)
6.2070 + ko.storedBindingContextForNode(node, bindingContextInstance);
6.2071 +
6.2072 + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
6.2073 + var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
6.2074 + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
6.2075 +
6.2076 + if (parsedBindings) {
6.2077 + // First run all the inits, so bindings can register for notification on changes
6.2078 + if (initPhase === 0) {
6.2079 + initPhase = 1;
6.2080 + for (var bindingKey in parsedBindings) {
6.2081 + var binding = ko.bindingHandlers[bindingKey];
6.2082 + if (binding && node.nodeType === 8)
6.2083 + validateThatBindingIsAllowedForVirtualElements(bindingKey);
6.2084 +
6.2085 + if (binding && typeof binding["init"] == "function") {
6.2086 + var handlerInitFn = binding["init"];
6.2087 + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
6.2088 +
6.2089 + // If this binding handler claims to control descendant bindings, make a note of this
6.2090 + if (initResult && initResult['controlsDescendantBindings']) {
6.2091 + if (bindingHandlerThatControlsDescendantBindings !== undefined)
6.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.");
6.2093 + bindingHandlerThatControlsDescendantBindings = bindingKey;
6.2094 + }
6.2095 + }
6.2096 + }
6.2097 + initPhase = 2;
6.2098 + }
6.2099 +
6.2100 + // ... then run all the updates, which might trigger changes even on the first evaluation
6.2101 + if (initPhase === 2) {
6.2102 + for (var bindingKey in parsedBindings) {
6.2103 + var binding = ko.bindingHandlers[bindingKey];
6.2104 + if (binding && typeof binding["update"] == "function") {
6.2105 + var handlerUpdateFn = binding["update"];
6.2106 + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
6.2107 + }
6.2108 + }
6.2109 + }
6.2110 + }
6.2111 + },
6.2112 + null,
6.2113 + { disposeWhenNodeIsRemoved : node }
6.2114 + );
6.2115 +
6.2116 + return {
6.2117 + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
6.2118 + };
6.2119 + };
6.2120 +
6.2121 + var storedBindingContextDomDataKey = "__ko_bindingContext__";
6.2122 + ko.storedBindingContextForNode = function (node, bindingContext) {
6.2123 + if (arguments.length == 2)
6.2124 + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
6.2125 + else
6.2126 + return ko.utils.domData.get(node, storedBindingContextDomDataKey);
6.2127 + }
6.2128 +
6.2129 + ko.applyBindingsToNode = function (node, bindings, viewModel) {
6.2130 + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
6.2131 + ko.virtualElements.normaliseVirtualElementDomStructure(node);
6.2132 + return applyBindingsToNodeInternal(node, bindings, viewModel, true);
6.2133 + };
6.2134 +
6.2135 + ko.applyBindingsToDescendants = function(viewModel, rootNode) {
6.2136 + if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
6.2137 + applyBindingsToDescendantsInternal(viewModel, rootNode, true);
6.2138 + };
6.2139 +
6.2140 + ko.applyBindings = function (viewModel, rootNode) {
6.2141 + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
6.2142 + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
6.2143 + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
6.2144 +
6.2145 + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
6.2146 + };
6.2147 +
6.2148 + // Retrieving binding context from arbitrary nodes
6.2149 + ko.contextFor = function(node) {
6.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)
6.2151 + switch (node.nodeType) {
6.2152 + case 1:
6.2153 + case 8:
6.2154 + var context = ko.storedBindingContextForNode(node);
6.2155 + if (context) return context;
6.2156 + if (node.parentNode) return ko.contextFor(node.parentNode);
6.2157 + break;
6.2158 + }
6.2159 + return undefined;
6.2160 + };
6.2161 + ko.dataFor = function(node) {
6.2162 + var context = ko.contextFor(node);
6.2163 + return context ? context['$data'] : undefined;
6.2164 + };
6.2165 +
6.2166 + ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
6.2167 + ko.exportSymbol('applyBindings', ko.applyBindings);
6.2168 + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
6.2169 + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
6.2170 + ko.exportSymbol('contextFor', ko.contextFor);
6.2171 + ko.exportSymbol('dataFor', ko.dataFor);
6.2172 +})();
6.2173 +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
6.2174 +ko.bindingHandlers['attr'] = {
6.2175 + 'update': function(element, valueAccessor, allBindingsAccessor) {
6.2176 + var value = ko.utils.unwrapObservable(valueAccessor()) || {};
6.2177 + for (var attrName in value) {
6.2178 + if (typeof attrName == "string") {
6.2179 + var attrValue = ko.utils.unwrapObservable(value[attrName]);
6.2180 +
6.2181 + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
6.2182 + // when someProp is a "no value"-like value (strictly null, false, or undefined)
6.2183 + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
6.2184 + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
6.2185 + if (toRemove)
6.2186 + element.removeAttribute(attrName);
6.2187 +
6.2188 + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
6.2189 + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
6.2190 + // but instead of figuring out the mode, we'll just set the attribute through the Javascript
6.2191 + // property for IE <= 8.
6.2192 + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
6.2193 + attrName = attrHtmlToJavascriptMap[attrName];
6.2194 + if (toRemove)
6.2195 + element.removeAttribute(attrName);
6.2196 + else
6.2197 + element[attrName] = attrValue;
6.2198 + } else if (!toRemove) {
6.2199 + try {
6.2200 + element.setAttribute(attrName, attrValue.toString());
6.2201 + } catch (err) {
6.2202 + // ignore for now
6.2203 + if (console) {
6.2204 + console.log("Can't set attribute " + attrName + " to " + attrValue + " error: " + err);
6.2205 + }
6.2206 + }
6.2207 + }
6.2208 +
6.2209 + // Treat "name" specially - although you can think of it as an attribute, it also needs
6.2210 + // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
6.2211 + // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
6.2212 + // entirely, and there's no strong reason to allow for such casing in HTML.
6.2213 + if (attrName === "name") {
6.2214 + ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
6.2215 + }
6.2216 + }
6.2217 + }
6.2218 + }
6.2219 +};
6.2220 +ko.bindingHandlers['checked'] = {
6.2221 + 'init': function (element, valueAccessor, allBindingsAccessor) {
6.2222 + var updateHandler = function() {
6.2223 + var valueToWrite;
6.2224 + if (element.type == "checkbox") {
6.2225 + valueToWrite = element.checked;
6.2226 + } else if ((element.type == "radio") && (element.checked)) {
6.2227 + valueToWrite = element.value;
6.2228 + } else {
6.2229 + return; // "checked" binding only responds to checkboxes and selected radio buttons
6.2230 + }
6.2231 +
6.2232 + var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
6.2233 + if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
6.2234 + // For checkboxes bound to an array, we add/remove the checkbox value to that array
6.2235 + // This works for both observable and non-observable arrays
6.2236 + var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
6.2237 + if (element.checked && (existingEntryIndex < 0))
6.2238 + modelValue.push(element.value);
6.2239 + else if ((!element.checked) && (existingEntryIndex >= 0))
6.2240 + modelValue.splice(existingEntryIndex, 1);
6.2241 + } else {
6.2242 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
6.2243 + }
6.2244 + };
6.2245 + ko.utils.registerEventHandler(element, "click", updateHandler);
6.2246 +
6.2247 + // IE 6 won't allow radio buttons to be selected unless they have a name
6.2248 + if ((element.type == "radio") && !element.name)
6.2249 + ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
6.2250 + },
6.2251 + 'update': function (element, valueAccessor) {
6.2252 + var value = ko.utils.unwrapObservable(valueAccessor());
6.2253 +
6.2254 + if (element.type == "checkbox") {
6.2255 + if (value instanceof Array) {
6.2256 + // When bound to an array, the checkbox being checked represents its value being present in that array
6.2257 + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0;
6.2258 + } else {
6.2259 + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish
6.2260 + element.checked = value;
6.2261 + }
6.2262 + } else if (element.type == "radio") {
6.2263 + element.checked = (element.value == value);
6.2264 + }
6.2265 + }
6.2266 +};
6.2267 +var classesWrittenByBindingKey = '__ko__cssValue';
6.2268 +ko.bindingHandlers['css'] = {
6.2269 + 'update': function (element, valueAccessor) {
6.2270 + var value = ko.utils.unwrapObservable(valueAccessor());
6.2271 + if (typeof value == "object") {
6.2272 + for (var className in value) {
6.2273 + var shouldHaveClass = ko.utils.unwrapObservable(value[className]);
6.2274 + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
6.2275 + }
6.2276 + } else {
6.2277 + value = String(value || ''); // Make sure we don't try to store or set a non-string value
6.2278 + ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
6.2279 + element[classesWrittenByBindingKey] = value;
6.2280 + ko.utils.toggleDomNodeCssClass(element, value, true);
6.2281 + }
6.2282 + }
6.2283 +};
6.2284 +ko.bindingHandlers['enable'] = {
6.2285 + 'update': function (element, valueAccessor) {
6.2286 + var value = ko.utils.unwrapObservable(valueAccessor());
6.2287 + if (value && element.disabled)
6.2288 + element.removeAttribute("disabled");
6.2289 + else if ((!value) && (!element.disabled))
6.2290 + element.disabled = true;
6.2291 + }
6.2292 +};
6.2293 +
6.2294 +ko.bindingHandlers['disable'] = {
6.2295 + 'update': function (element, valueAccessor) {
6.2296 + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
6.2297 + }
6.2298 +};
6.2299 +// For certain common events (currently just 'click'), allow a simplified data-binding syntax
6.2300 +// e.g. click:handler instead of the usual full-length event:{click:handler}
6.2301 +function makeEventHandlerShortcut(eventName) {
6.2302 + ko.bindingHandlers[eventName] = {
6.2303 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) {
6.2304 + var newValueAccessor = function () {
6.2305 + var result = {};
6.2306 + result[eventName] = valueAccessor();
6.2307 + return result;
6.2308 + };
6.2309 + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel);
6.2310 + }
6.2311 + }
6.2312 +}
6.2313 +
6.2314 +ko.bindingHandlers['event'] = {
6.2315 + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) {
6.2316 + var eventsToHandle = valueAccessor() || {};
6.2317 + for(var eventNameOutsideClosure in eventsToHandle) {
6.2318 + (function() {
6.2319 + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure
6.2320 + if (typeof eventName == "string") {
6.2321 + ko.utils.registerEventHandler(element, eventName, function (event) {
6.2322 + var handlerReturnValue;
6.2323 + var handlerFunction = valueAccessor()[eventName];
6.2324 + if (!handlerFunction)
6.2325 + return;
6.2326 + var allBindings = allBindingsAccessor();
6.2327 +
6.2328 + try {
6.2329 + // Take all the event args, and prefix with the viewmodel
6.2330 + var argsForHandler = ko.utils.makeArray(arguments);
6.2331 + argsForHandler.unshift(viewModel);
6.2332 + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
6.2333 + } finally {
6.2334 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
6.2335 + if (event.preventDefault)
6.2336 + event.preventDefault();
6.2337 + else
6.2338 + event.returnValue = false;
6.2339 + }
6.2340 + }
6.2341 +
6.2342 + var bubble = allBindings[eventName + 'Bubble'] !== false;
6.2343 + if (!bubble) {
6.2344 + event.cancelBubble = true;
6.2345 + if (event.stopPropagation)
6.2346 + event.stopPropagation();
6.2347 + }
6.2348 + });
6.2349 + }
6.2350 + })();
6.2351 + }
6.2352 + }
6.2353 +};
6.2354 +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
6.2355 +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
6.2356 +ko.bindingHandlers['foreach'] = {
6.2357 + makeTemplateValueAccessor: function(valueAccessor) {
6.2358 + return function() {
6.2359 + var modelValue = valueAccessor(),
6.2360 + unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
6.2361 +
6.2362 + // If unwrappedValue is the array, pass in the wrapped value on its own
6.2363 + // The value will be unwrapped and tracked within the template binding
6.2364 + // (See https://github.com/SteveSanderson/knockout/issues/523)
6.2365 + if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
6.2366 + return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
6.2367 +
6.2368 + // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
6.2369 + ko.utils.unwrapObservable(modelValue);
6.2370 + return {
6.2371 + 'foreach': unwrappedValue['data'],
6.2372 + 'as': unwrappedValue['as'],
6.2373 + 'includeDestroyed': unwrappedValue['includeDestroyed'],
6.2374 + 'afterAdd': unwrappedValue['afterAdd'],
6.2375 + 'beforeRemove': unwrappedValue['beforeRemove'],
6.2376 + 'afterRender': unwrappedValue['afterRender'],
6.2377 + 'beforeMove': unwrappedValue['beforeMove'],
6.2378 + 'afterMove': unwrappedValue['afterMove'],
6.2379 + 'templateEngine': ko.nativeTemplateEngine.instance
6.2380 + };
6.2381 + };
6.2382 + },
6.2383 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2384 + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
6.2385 + },
6.2386 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2387 + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext);
6.2388 + }
6.2389 +};
6.2390 +ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
6.2391 +ko.virtualElements.allowedBindings['foreach'] = true;
6.2392 +var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
6.2393 +ko.bindingHandlers['hasfocus'] = {
6.2394 + 'init': function(element, valueAccessor, allBindingsAccessor) {
6.2395 + var handleElementFocusChange = function(isFocused) {
6.2396 + // Where possible, ignore which event was raised and determine focus state using activeElement,
6.2397 + // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
6.2398 + // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
6.2399 + // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
6.2400 + // from calling 'blur()' on the element when it loses focus.
6.2401 + // Discussion at https://github.com/SteveSanderson/knockout/pull/352
6.2402 + element[hasfocusUpdatingProperty] = true;
6.2403 + var ownerDoc = element.ownerDocument;
6.2404 + if ("activeElement" in ownerDoc) {
6.2405 + isFocused = (ownerDoc.activeElement === element);
6.2406 + }
6.2407 + var modelValue = valueAccessor();
6.2408 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', isFocused, true);
6.2409 + element[hasfocusUpdatingProperty] = false;
6.2410 + };
6.2411 + var handleElementFocusIn = handleElementFocusChange.bind(null, true);
6.2412 + var handleElementFocusOut = handleElementFocusChange.bind(null, false);
6.2413 +
6.2414 + ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
6.2415 + ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
6.2416 + ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
6.2417 + ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
6.2418 + },
6.2419 + 'update': function(element, valueAccessor) {
6.2420 + var value = ko.utils.unwrapObservable(valueAccessor());
6.2421 + if (!element[hasfocusUpdatingProperty]) {
6.2422 + value ? element.focus() : element.blur();
6.2423 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
6.2424 + }
6.2425 + }
6.2426 +};
6.2427 +ko.bindingHandlers['html'] = {
6.2428 + 'init': function() {
6.2429 + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
6.2430 + return { 'controlsDescendantBindings': true };
6.2431 + },
6.2432 + 'update': function (element, valueAccessor) {
6.2433 + // setHtml will unwrap the value if needed
6.2434 + ko.utils.setHtml(element, valueAccessor());
6.2435 + }
6.2436 +};
6.2437 +var withIfDomDataKey = '__ko_withIfBindingData';
6.2438 +// Makes a binding like with or if
6.2439 +function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
6.2440 + ko.bindingHandlers[bindingKey] = {
6.2441 + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2442 + ko.utils.domData.set(element, withIfDomDataKey, {});
6.2443 + return { 'controlsDescendantBindings': true };
6.2444 + },
6.2445 + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.2446 + var withIfData = ko.utils.domData.get(element, withIfDomDataKey),
6.2447 + dataValue = ko.utils.unwrapObservable(valueAccessor()),
6.2448 + shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
6.2449 + isFirstRender = !withIfData.savedNodes,
6.2450 + needsRefresh = isFirstRender || isWith || (shouldDisplay !== withIfData.didDisplayOnLastUpdate);
6.2451 +
6.2452 + if (needsRefresh) {
6.2453 + if (isFirstRender) {
6.2454 + withIfData.savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
6.2455 + }
6.2456 +
6.2457 + if (shouldDisplay) {
6.2458 + if (!isFirstRender) {
6.2459 + ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(withIfData.savedNodes));
6.2460 + }
6.2461 + ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
6.2462 + } else {
6.2463 + ko.virtualElements.emptyNode(element);
6.2464 + }
6.2465 +
6.2466 + withIfData.didDisplayOnLastUpdate = shouldDisplay;
6.2467 + }
6.2468 + }
6.2469 + };
6.2470 + ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
6.2471 + ko.virtualElements.allowedBindings[bindingKey] = true;
6.2472 +}
6.2473 +
6.2474 +// Construct the actual binding handlers
6.2475 +makeWithIfBinding('if');
6.2476 +makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
6.2477 +makeWithIfBinding('with', true /* isWith */, false /* isNot */,
6.2478 + function(bindingContext, dataValue) {
6.2479 + return bindingContext['createChildContext'](dataValue);
6.2480 + }
6.2481 +);
6.2482 +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
6.2483 + if (preferModelValue) {
6.2484 + if (modelValue !== ko.selectExtensions.readValue(element))
6.2485 + ko.selectExtensions.writeValue(element, modelValue);
6.2486 + }
6.2487 +
6.2488 + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
6.2489 + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
6.2490 + // change the model value to match the dropdown.
6.2491 + if (modelValue !== ko.selectExtensions.readValue(element))
6.2492 + ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
6.2493 +};
6.2494 +
6.2495 +ko.bindingHandlers['options'] = {
6.2496 + 'update': function (element, valueAccessor, allBindingsAccessor) {
6.2497 + if (ko.utils.tagNameLower(element) !== "select")
6.2498 + throw new Error("options binding applies only to SELECT elements");
6.2499 +
6.2500 + var selectWasPreviouslyEmpty = element.length == 0;
6.2501 + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
6.2502 + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
6.2503 + }), function (node) {
6.2504 + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
6.2505 + });
6.2506 + var previousScrollTop = element.scrollTop;
6.2507 +
6.2508 + var value = ko.utils.unwrapObservable(valueAccessor());
6.2509 + var selectedValue = element.value;
6.2510 +
6.2511 + // Remove all existing <option>s.
6.2512 + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
6.2513 + while (element.length > 0) {
6.2514 + ko.cleanNode(element.options[0]);
6.2515 + element.remove(0);
6.2516 + }
6.2517 +
6.2518 + if (value) {
6.2519 + var allBindings = allBindingsAccessor(),
6.2520 + includeDestroyed = allBindings['optionsIncludeDestroyed'];
6.2521 +
6.2522 + if (typeof value.length != "number")
6.2523 + value = [value];
6.2524 + if (allBindings['optionsCaption']) {
6.2525 + var option = document.createElement("option");
6.2526 + ko.utils.setHtml(option, allBindings['optionsCaption']);
6.2527 + ko.selectExtensions.writeValue(option, undefined);
6.2528 + element.appendChild(option);
6.2529 + }
6.2530 +
6.2531 + for (var i = 0, j = value.length; i < j; i++) {
6.2532 + // Skip destroyed items
6.2533 + var arrayEntry = value[i];
6.2534 + if (arrayEntry && arrayEntry['_destroy'] && !includeDestroyed)
6.2535 + continue;
6.2536 +
6.2537 + var option = document.createElement("option");
6.2538 +
6.2539 + function applyToObject(object, predicate, defaultValue) {
6.2540 + var predicateType = typeof predicate;
6.2541 + if (predicateType == "function") // Given a function; run it against the data value
6.2542 + return predicate(object);
6.2543 + else if (predicateType == "string") // Given a string; treat it as a property name on the data value
6.2544 + return object[predicate];
6.2545 + else // Given no optionsText arg; use the data value itself
6.2546 + return defaultValue;
6.2547 + }
6.2548 +
6.2549 + // Apply a value to the option element
6.2550 + var optionValue = applyToObject(arrayEntry, allBindings['optionsValue'], arrayEntry);
6.2551 + ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
6.2552 +
6.2553 + // Apply some text to the option element
6.2554 + var optionText = applyToObject(arrayEntry, allBindings['optionsText'], optionValue);
6.2555 + ko.utils.setTextContent(option, optionText);
6.2556 +
6.2557 + element.appendChild(option);
6.2558 + }
6.2559 +
6.2560 + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
6.2561 + // That's why we first added them without selection. Now it's time to set the selection.
6.2562 + var newOptions = element.getElementsByTagName("option");
6.2563 + var countSelectionsRetained = 0;
6.2564 + for (var i = 0, j = newOptions.length; i < j; i++) {
6.2565 + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
6.2566 + ko.utils.setOptionNodeSelectionState(newOptions[i], true);
6.2567 + countSelectionsRetained++;
6.2568 + }
6.2569 + }
6.2570 +
6.2571 + element.scrollTop = previousScrollTop;
6.2572 +
6.2573 + if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
6.2574 + // Ensure consistency between model value and selected option.
6.2575 + // If the dropdown is being populated for the first time here (or was otherwise previously empty),
6.2576 + // the dropdown selection state is meaningless, so we preserve the model value.
6.2577 + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.peekObservable(allBindings['value']), /* preferModelValue */ true);
6.2578 + }
6.2579 +
6.2580 + // Workaround for IE9 bug
6.2581 + ko.utils.ensureSelectElementIsRenderedCorrectly(element);
6.2582 + }
6.2583 + }
6.2584 +};
6.2585 +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__';
6.2586 +ko.bindingHandlers['selectedOptions'] = {
6.2587 + 'init': function (element, valueAccessor, allBindingsAccessor) {
6.2588 + ko.utils.registerEventHandler(element, "change", function () {
6.2589 + var value = valueAccessor(), valueToWrite = [];
6.2590 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
6.2591 + if (node.selected)
6.2592 + valueToWrite.push(ko.selectExtensions.readValue(node));
6.2593 + });
6.2594 + ko.expressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite);
6.2595 + });
6.2596 + },
6.2597 + 'update': function (element, valueAccessor) {
6.2598 + if (ko.utils.tagNameLower(element) != "select")
6.2599 + throw new Error("values binding applies only to SELECT elements");
6.2600 +
6.2601 + var newValue = ko.utils.unwrapObservable(valueAccessor());
6.2602 + if (newValue && typeof newValue.length == "number") {
6.2603 + ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
6.2604 + var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
6.2605 + ko.utils.setOptionNodeSelectionState(node, isSelected);
6.2606 + });
6.2607 + }
6.2608 + }
6.2609 +};
6.2610 +ko.bindingHandlers['style'] = {
6.2611 + 'update': function (element, valueAccessor) {
6.2612 + var value = ko.utils.unwrapObservable(valueAccessor() || {});
6.2613 + for (var styleName in value) {
6.2614 + if (typeof styleName == "string") {
6.2615 + var styleValue = ko.utils.unwrapObservable(value[styleName]);
6.2616 + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
6.2617 + }
6.2618 + }
6.2619 + }
6.2620 +};
6.2621 +ko.bindingHandlers['submit'] = {
6.2622 + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
6.2623 + if (typeof valueAccessor() != "function")
6.2624 + throw new Error("The value for a submit binding must be a function");
6.2625 + ko.utils.registerEventHandler(element, "submit", function (event) {
6.2626 + var handlerReturnValue;
6.2627 + var value = valueAccessor();
6.2628 + try { handlerReturnValue = value.call(viewModel, element); }
6.2629 + finally {
6.2630 + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
6.2631 + if (event.preventDefault)
6.2632 + event.preventDefault();
6.2633 + else
6.2634 + event.returnValue = false;
6.2635 + }
6.2636 + }
6.2637 + });
6.2638 + }
6.2639 +};
6.2640 +ko.bindingHandlers['text'] = {
6.2641 + 'update': function (element, valueAccessor) {
6.2642 + ko.utils.setTextContent(element, valueAccessor());
6.2643 + }
6.2644 +};
6.2645 +ko.virtualElements.allowedBindings['text'] = true;
6.2646 +ko.bindingHandlers['uniqueName'] = {
6.2647 + 'init': function (element, valueAccessor) {
6.2648 + if (valueAccessor()) {
6.2649 + var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
6.2650 + ko.utils.setElementName(element, name);
6.2651 + }
6.2652 + }
6.2653 +};
6.2654 +ko.bindingHandlers['uniqueName'].currentIndex = 0;
6.2655 +ko.bindingHandlers['value'] = {
6.2656 + 'init': function (element, valueAccessor, allBindingsAccessor) {
6.2657 + // Always catch "change" event; possibly other events too if asked
6.2658 + var eventsToCatch = ["change"];
6.2659 + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"];
6.2660 + var propertyChangedFired = false;
6.2661 + if (requestedEventsToCatch) {
6.2662 + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
6.2663 + requestedEventsToCatch = [requestedEventsToCatch];
6.2664 + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
6.2665 + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
6.2666 + }
6.2667 +
6.2668 + var valueUpdateHandler = function() {
6.2669 + propertyChangedFired = false;
6.2670 + var modelValue = valueAccessor();
6.2671 + var elementValue = ko.selectExtensions.readValue(element);
6.2672 + ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
6.2673 + }
6.2674 +
6.2675 + // Workaround for https://github.com/SteveSanderson/knockout/issues/122
6.2676 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
6.2677 + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
6.2678 + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
6.2679 + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
6.2680 + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
6.2681 + ko.utils.registerEventHandler(element, "blur", function() {
6.2682 + if (propertyChangedFired) {
6.2683 + valueUpdateHandler();
6.2684 + }
6.2685 + });
6.2686 + }
6.2687 +
6.2688 + ko.utils.arrayForEach(eventsToCatch, function(eventName) {
6.2689 + // The syntax "after<eventname>" means "run the handler asynchronously after the event"
6.2690 + // This is useful, for example, to catch "keydown" events after the browser has updated the control
6.2691 + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
6.2692 + var handler = valueUpdateHandler;
6.2693 + if (ko.utils.stringStartsWith(eventName, "after")) {
6.2694 + handler = function() { setTimeout(valueUpdateHandler, 0) };
6.2695 + eventName = eventName.substring("after".length);
6.2696 + }
6.2697 + ko.utils.registerEventHandler(element, eventName, handler);
6.2698 + });
6.2699 + },
6.2700 + 'update': function (element, valueAccessor) {
6.2701 + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select";
6.2702 + var newValue = ko.utils.unwrapObservable(valueAccessor());
6.2703 + var elementValue = ko.selectExtensions.readValue(element);
6.2704 + var valueHasChanged = (newValue != elementValue);
6.2705 +
6.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).
6.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.
6.2708 + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0"))
6.2709 + valueHasChanged = true;
6.2710 +
6.2711 + if (valueHasChanged) {
6.2712 + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); };
6.2713 + applyValueAction();
6.2714 +
6.2715 + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
6.2716 + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
6.2717 + // to apply the value as well.
6.2718 + var alsoApplyAsynchronously = valueIsSelectOption;
6.2719 + if (alsoApplyAsynchronously)
6.2720 + setTimeout(applyValueAction, 0);
6.2721 + }
6.2722 +
6.2723 + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
6.2724 + // because you're not allowed to have a model value that disagrees with a visible UI selection.
6.2725 + if (valueIsSelectOption && (element.length > 0))
6.2726 + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false);
6.2727 + }
6.2728 +};
6.2729 +ko.bindingHandlers['visible'] = {
6.2730 + 'update': function (element, valueAccessor) {
6.2731 + var value = ko.utils.unwrapObservable(valueAccessor());
6.2732 + var isCurrentlyVisible = !(element.style.display == "none");
6.2733 + if (value && !isCurrentlyVisible)
6.2734 + element.style.display = "";
6.2735 + else if ((!value) && isCurrentlyVisible)
6.2736 + element.style.display = "none";
6.2737 + }
6.2738 +};
6.2739 +// 'click' is just a shorthand for the usual full-length event:{click:handler}
6.2740 +makeEventHandlerShortcut('click');
6.2741 +// If you want to make a custom template engine,
6.2742 +//
6.2743 +// [1] Inherit from this class (like ko.nativeTemplateEngine does)
6.2744 +// [2] Override 'renderTemplateSource', supplying a function with this signature:
6.2745 +//
6.2746 +// function (templateSource, bindingContext, options) {
6.2747 +// // - templateSource.text() is the text of the template you should render
6.2748 +// // - bindingContext.$data is the data you should pass into the template
6.2749 +// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
6.2750 +// // and bindingContext.$root available in the template too
6.2751 +// // - options gives you access to any other properties set on "data-bind: { template: options }"
6.2752 +// //
6.2753 +// // Return value: an array of DOM nodes
6.2754 +// }
6.2755 +//
6.2756 +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
6.2757 +//
6.2758 +// function (script) {
6.2759 +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
6.2760 +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
6.2761 +// }
6.2762 +//
6.2763 +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
6.2764 +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
6.2765 +// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
6.2766 +
6.2767 +ko.templateEngine = function () { };
6.2768 +
6.2769 +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
6.2770 + throw new Error("Override renderTemplateSource");
6.2771 +};
6.2772 +
6.2773 +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
6.2774 + throw new Error("Override createJavaScriptEvaluatorBlock");
6.2775 +};
6.2776 +
6.2777 +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
6.2778 + // Named template
6.2779 + if (typeof template == "string") {
6.2780 + templateDocument = templateDocument || document;
6.2781 + var elem = templateDocument.getElementById(template);
6.2782 + if (!elem)
6.2783 + throw new Error("Cannot find template with ID " + template);
6.2784 + return new ko.templateSources.domElement(elem);
6.2785 + } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
6.2786 + // Anonymous template
6.2787 + return new ko.templateSources.anonymousTemplate(template);
6.2788 + } else
6.2789 + throw new Error("Unknown template type: " + template);
6.2790 +};
6.2791 +
6.2792 +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
6.2793 + var templateSource = this['makeTemplateSource'](template, templateDocument);
6.2794 + return this['renderTemplateSource'](templateSource, bindingContext, options);
6.2795 +};
6.2796 +
6.2797 +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
6.2798 + // Skip rewriting if requested
6.2799 + if (this['allowTemplateRewriting'] === false)
6.2800 + return true;
6.2801 + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
6.2802 +};
6.2803 +
6.2804 +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
6.2805 + var templateSource = this['makeTemplateSource'](template, templateDocument);
6.2806 + var rewritten = rewriterCallback(templateSource['text']());
6.2807 + templateSource['text'](rewritten);
6.2808 + templateSource['data']("isRewritten", true);
6.2809 +};
6.2810 +
6.2811 +ko.exportSymbol('templateEngine', ko.templateEngine);
6.2812 +
6.2813 +ko.templateRewriting = (function () {
6.2814 + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi;
6.2815 + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
6.2816 +
6.2817 + function validateDataBindValuesForRewriting(keyValueArray) {
6.2818 + var allValidators = ko.expressionRewriting.bindingRewriteValidators;
6.2819 + for (var i = 0; i < keyValueArray.length; i++) {
6.2820 + var key = keyValueArray[i]['key'];
6.2821 + if (allValidators.hasOwnProperty(key)) {
6.2822 + var validator = allValidators[key];
6.2823 +
6.2824 + if (typeof validator === "function") {
6.2825 + var possibleErrorMessage = validator(keyValueArray[i]['value']);
6.2826 + if (possibleErrorMessage)
6.2827 + throw new Error(possibleErrorMessage);
6.2828 + } else if (!validator) {
6.2829 + throw new Error("This template engine does not support the '" + key + "' binding within its templates");
6.2830 + }
6.2831 + }
6.2832 + }
6.2833 + }
6.2834 +
6.2835 + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) {
6.2836 + var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
6.2837 + validateDataBindValuesForRewriting(dataBindKeyValueArray);
6.2838 + var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray);
6.2839 +
6.2840 + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
6.2841 + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
6.2842 + // extra indirection.
6.2843 + var applyBindingsToNextSiblingScript =
6.2844 + "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()})";
6.2845 + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
6.2846 + }
6.2847 +
6.2848 + return {
6.2849 + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
6.2850 + if (!templateEngine['isTemplateRewritten'](template, templateDocument))
6.2851 + templateEngine['rewriteTemplate'](template, function (htmlString) {
6.2852 + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
6.2853 + }, templateDocument);
6.2854 + },
6.2855 +
6.2856 + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
6.2857 + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
6.2858 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine);
6.2859 + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
6.2860 + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine);
6.2861 + });
6.2862 + },
6.2863 +
6.2864 + applyMemoizedBindingsToNextSibling: function (bindings) {
6.2865 + return ko.memoization.memoize(function (domNode, bindingContext) {
6.2866 + if (domNode.nextSibling)
6.2867 + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext);
6.2868 + });
6.2869 + }
6.2870 + }
6.2871 +})();
6.2872 +
6.2873 +
6.2874 +// Exported only because it has to be referenced by string lookup from within rewritten template
6.2875 +ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
6.2876 +(function() {
6.2877 + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
6.2878 + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
6.2879 + //
6.2880 + // Two are provided by default:
6.2881 + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
6.2882 + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
6.2883 + // without reading/writing the actual element text content, since it will be overwritten
6.2884 + // with the rendered template output.
6.2885 + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
6.2886 + // Template sources need to have the following functions:
6.2887 + // text() - returns the template text from your storage location
6.2888 + // text(value) - writes the supplied template text to your storage location
6.2889 + // data(key) - reads values stored using data(key, value) - see below
6.2890 + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
6.2891 + //
6.2892 + // Optionally, template sources can also have the following functions:
6.2893 + // nodes() - returns a DOM element containing the nodes of this template, where available
6.2894 + // nodes(value) - writes the given DOM element to your storage location
6.2895 + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
6.2896 + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
6.2897 + //
6.2898 + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
6.2899 + // using and overriding "makeTemplateSource" to return an instance of your custom template source.
6.2900 +
6.2901 + ko.templateSources = {};
6.2902 +
6.2903 + // ---- ko.templateSources.domElement -----
6.2904 +
6.2905 + ko.templateSources.domElement = function(element) {
6.2906 + this.domElement = element;
6.2907 + }
6.2908 +
6.2909 + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
6.2910 + var tagNameLower = ko.utils.tagNameLower(this.domElement),
6.2911 + elemContentsProperty = tagNameLower === "script" ? "text"
6.2912 + : tagNameLower === "textarea" ? "value"
6.2913 + : "innerHTML";
6.2914 +
6.2915 + if (arguments.length == 0) {
6.2916 + return this.domElement[elemContentsProperty];
6.2917 + } else {
6.2918 + var valueToWrite = arguments[0];
6.2919 + if (elemContentsProperty === "innerHTML")
6.2920 + ko.utils.setHtml(this.domElement, valueToWrite);
6.2921 + else
6.2922 + this.domElement[elemContentsProperty] = valueToWrite;
6.2923 + }
6.2924 + };
6.2925 +
6.2926 + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
6.2927 + if (arguments.length === 1) {
6.2928 + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key);
6.2929 + } else {
6.2930 + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]);
6.2931 + }
6.2932 + };
6.2933 +
6.2934 + // ---- ko.templateSources.anonymousTemplate -----
6.2935 + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
6.2936 + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
6.2937 + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
6.2938 +
6.2939 + var anonymousTemplatesDomDataKey = "__ko_anon_template__";
6.2940 + ko.templateSources.anonymousTemplate = function(element) {
6.2941 + this.domElement = element;
6.2942 + }
6.2943 + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
6.2944 + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
6.2945 + if (arguments.length == 0) {
6.2946 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
6.2947 + if (templateData.textData === undefined && templateData.containerData)
6.2948 + templateData.textData = templateData.containerData.innerHTML;
6.2949 + return templateData.textData;
6.2950 + } else {
6.2951 + var valueToWrite = arguments[0];
6.2952 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
6.2953 + }
6.2954 + };
6.2955 + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
6.2956 + if (arguments.length == 0) {
6.2957 + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
6.2958 + return templateData.containerData;
6.2959 + } else {
6.2960 + var valueToWrite = arguments[0];
6.2961 + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
6.2962 + }
6.2963 + };
6.2964 +
6.2965 + ko.exportSymbol('templateSources', ko.templateSources);
6.2966 + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
6.2967 + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
6.2968 +})();
6.2969 +(function () {
6.2970 + var _templateEngine;
6.2971 + ko.setTemplateEngine = function (templateEngine) {
6.2972 + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
6.2973 + throw new Error("templateEngine must inherit from ko.templateEngine");
6.2974 + _templateEngine = templateEngine;
6.2975 + }
6.2976 +
6.2977 + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) {
6.2978 + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
6.2979 + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
6.2980 + nextInQueue = ko.virtualElements.nextSibling(node);
6.2981 + if (node.nodeType === 1 || node.nodeType === 8)
6.2982 + action(node);
6.2983 + }
6.2984 + }
6.2985 +
6.2986 + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
6.2987 + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
6.2988 + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
6.2989 + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
6.2990 + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
6.2991 + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
6.2992 +
6.2993 + if (continuousNodeArray.length) {
6.2994 + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1];
6.2995 +
6.2996 + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
6.2997 + // whereas a regular applyBindings won't introduce new memoized nodes
6.2998 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
6.2999 + ko.applyBindings(bindingContext, node);
6.3000 + });
6.3001 + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) {
6.3002 + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
6.3003 + });
6.3004 + }
6.3005 + }
6.3006 +
6.3007 + function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
6.3008 + return nodeOrNodeArray.nodeType ? nodeOrNodeArray
6.3009 + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
6.3010 + : null;
6.3011 + }
6.3012 +
6.3013 + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
6.3014 + options = options || {};
6.3015 + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
6.3016 + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
6.3017 + var templateEngineToUse = (options['templateEngine'] || _templateEngine);
6.3018 + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
6.3019 + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
6.3020 +
6.3021 + // Loosely check result is an array of DOM nodes
6.3022 + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
6.3023 + throw new Error("Template engine must return an array of DOM nodes");
6.3024 +
6.3025 + var haveAddedNodesToParent = false;
6.3026 + switch (renderMode) {
6.3027 + case "replaceChildren":
6.3028 + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
6.3029 + haveAddedNodesToParent = true;
6.3030 + break;
6.3031 + case "replaceNode":
6.3032 + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
6.3033 + haveAddedNodesToParent = true;
6.3034 + break;
6.3035 + case "ignoreTargetNode": break;
6.3036 + default:
6.3037 + throw new Error("Unknown renderMode: " + renderMode);
6.3038 + }
6.3039 +
6.3040 + if (haveAddedNodesToParent) {
6.3041 + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
6.3042 + if (options['afterRender'])
6.3043 + ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
6.3044 + }
6.3045 +
6.3046 + return renderedNodesArray;
6.3047 + }
6.3048 +
6.3049 + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
6.3050 + options = options || {};
6.3051 + if ((options['templateEngine'] || _templateEngine) == undefined)
6.3052 + throw new Error("Set a template engine before calling renderTemplate");
6.3053 + renderMode = renderMode || "replaceChildren";
6.3054 +
6.3055 + if (targetNodeOrNodeArray) {
6.3056 + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
6.3057 +
6.3058 + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
6.3059 + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
6.3060 +
6.3061 + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
6.3062 + function () {
6.3063 + // Ensure we've got a proper binding context to work with
6.3064 + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
6.3065 + ? dataOrBindingContext
6.3066 + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
6.3067 +
6.3068 + // Support selecting template as a function of the data being rendered
6.3069 + var templateName = typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
6.3070 +
6.3071 + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
6.3072 + if (renderMode == "replaceNode") {
6.3073 + targetNodeOrNodeArray = renderedNodesArray;
6.3074 + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
6.3075 + }
6.3076 + },
6.3077 + null,
6.3078 + { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
6.3079 + );
6.3080 + } else {
6.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
6.3082 + return ko.memoization.memoize(function (domNode) {
6.3083 + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
6.3084 + });
6.3085 + }
6.3086 + };
6.3087 +
6.3088 + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
6.3089 + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
6.3090 + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
6.3091 + var arrayItemContext;
6.3092 +
6.3093 + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
6.3094 + var executeTemplateForArrayItem = function (arrayValue, index) {
6.3095 + // Support selecting template as a function of the data being rendered
6.3096 + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue), options['as']);
6.3097 + arrayItemContext['$index'] = index;
6.3098 + var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
6.3099 + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
6.3100 + }
6.3101 +
6.3102 + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
6.3103 + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
6.3104 + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
6.3105 + if (options['afterRender'])
6.3106 + options['afterRender'](addedNodesArray, arrayValue);
6.3107 + };
6.3108 +
6.3109 + return ko.dependentObservable(function () {
6.3110 + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
6.3111 + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
6.3112 + unwrappedArray = [unwrappedArray];
6.3113 +
6.3114 + // Filter out any entries marked as destroyed
6.3115 + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
6.3116 + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
6.3117 + });
6.3118 +
6.3119 + // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
6.3120 + // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
6.3121 + ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
6.3122 +
6.3123 + }, null, { disposeWhenNodeIsRemoved: targetNode });
6.3124 + };
6.3125 +
6.3126 + var templateComputedDomDataKey = '__ko__templateComputedDomDataKey__';
6.3127 + function disposeOldComputedAndStoreNewOne(element, newComputed) {
6.3128 + var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
6.3129 + if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
6.3130 + oldComputed.dispose();
6.3131 + ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
6.3132 + }
6.3133 +
6.3134 + ko.bindingHandlers['template'] = {
6.3135 + 'init': function(element, valueAccessor) {
6.3136 + // Support anonymous templates
6.3137 + var bindingValue = ko.utils.unwrapObservable(valueAccessor());
6.3138 + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) {
6.3139 + // It's an anonymous template - store the element contents, then clear the element
6.3140 + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element),
6.3141 + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
6.3142 + new ko.templateSources.anonymousTemplate(element)['nodes'](container);
6.3143 + }
6.3144 + return { 'controlsDescendantBindings': true };
6.3145 + },
6.3146 + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
6.3147 + var templateName = ko.utils.unwrapObservable(valueAccessor()),
6.3148 + options = {},
6.3149 + shouldDisplay = true,
6.3150 + dataValue,
6.3151 + templateComputed = null;
6.3152 +
6.3153 + if (typeof templateName != "string") {
6.3154 + options = templateName;
6.3155 + templateName = options['name'];
6.3156 +
6.3157 + // Support "if"/"ifnot" conditions
6.3158 + if ('if' in options)
6.3159 + shouldDisplay = ko.utils.unwrapObservable(options['if']);
6.3160 + if (shouldDisplay && 'ifnot' in options)
6.3161 + shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
6.3162 +
6.3163 + dataValue = ko.utils.unwrapObservable(options['data']);
6.3164 + }
6.3165 +
6.3166 + if ('foreach' in options) {
6.3167 + // Render once for each data point (treating data set as empty if shouldDisplay==false)
6.3168 + var dataArray = (shouldDisplay && options['foreach']) || [];
6.3169 + templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
6.3170 + } else if (!shouldDisplay) {
6.3171 + ko.virtualElements.emptyNode(element);
6.3172 + } else {
6.3173 + // Render once for this single data point (or use the viewModel if no data was provided)
6.3174 + var innerBindingContext = ('data' in options) ?
6.3175 + bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
6.3176 + bindingContext; // Given no explicit 'data' value, we retain the same binding context
6.3177 + templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
6.3178 + }
6.3179 +
6.3180 + // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
6.3181 + disposeOldComputedAndStoreNewOne(element, templateComputed);
6.3182 + }
6.3183 + };
6.3184 +
6.3185 + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
6.3186 + ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
6.3187 + var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
6.3188 +
6.3189 + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
6.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)
6.3191 +
6.3192 + if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
6.3193 + return null; // Named templates can be rewritten, so return "no error"
6.3194 + return "This template engine does not support anonymous templates nested within its templates";
6.3195 + };
6.3196 +
6.3197 + ko.virtualElements.allowedBindings['template'] = true;
6.3198 +})();
6.3199 +
6.3200 +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
6.3201 +ko.exportSymbol('renderTemplate', ko.renderTemplate);
6.3202 +
6.3203 +ko.utils.compareArrays = (function () {
6.3204 + var statusNotInOld = 'added', statusNotInNew = 'deleted';
6.3205 +
6.3206 + // Simple calculation based on Levenshtein distance.
6.3207 + function compareArrays(oldArray, newArray, dontLimitMoves) {
6.3208 + oldArray = oldArray || [];
6.3209 + newArray = newArray || [];
6.3210 +
6.3211 + if (oldArray.length <= newArray.length)
6.3212 + return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, dontLimitMoves);
6.3213 + else
6.3214 + return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, dontLimitMoves);
6.3215 + }
6.3216 +
6.3217 + function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, dontLimitMoves) {
6.3218 + var myMin = Math.min,
6.3219 + myMax = Math.max,
6.3220 + editDistanceMatrix = [],
6.3221 + smlIndex, smlIndexMax = smlArray.length,
6.3222 + bigIndex, bigIndexMax = bigArray.length,
6.3223 + compareRange = (bigIndexMax - smlIndexMax) || 1,
6.3224 + maxDistance = smlIndexMax + bigIndexMax + 1,
6.3225 + thisRow, lastRow,
6.3226 + bigIndexMaxForRow, bigIndexMinForRow;
6.3227 +
6.3228 + for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
6.3229 + lastRow = thisRow;
6.3230 + editDistanceMatrix.push(thisRow = []);
6.3231 + bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
6.3232 + bigIndexMinForRow = myMax(0, smlIndex - 1);
6.3233 + for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
6.3234 + if (!bigIndex)
6.3235 + thisRow[bigIndex] = smlIndex + 1;
6.3236 + else if (!smlIndex) // Top row - transform empty array into new array via additions
6.3237 + thisRow[bigIndex] = bigIndex + 1;
6.3238 + else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
6.3239 + thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
6.3240 + else {
6.3241 + var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
6.3242 + var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
6.3243 + thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
6.3244 + }
6.3245 + }
6.3246 + }
6.3247 +
6.3248 + var editScript = [], meMinusOne, notInSml = [], notInBig = [];
6.3249 + for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
6.3250 + meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
6.3251 + if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
6.3252 + notInSml.push(editScript[editScript.length] = { // added
6.3253 + 'status': statusNotInSml,
6.3254 + 'value': bigArray[--bigIndex],
6.3255 + 'index': bigIndex });
6.3256 + } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
6.3257 + notInBig.push(editScript[editScript.length] = { // deleted
6.3258 + 'status': statusNotInBig,
6.3259 + 'value': smlArray[--smlIndex],
6.3260 + 'index': smlIndex });
6.3261 + } else {
6.3262 + editScript.push({
6.3263 + 'status': "retained",
6.3264 + 'value': bigArray[--bigIndex] });
6.3265 + --smlIndex;
6.3266 + }
6.3267 + }
6.3268 +
6.3269 + if (notInSml.length && notInBig.length) {
6.3270 + // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
6.3271 + // smlIndexMax keeps the time complexity of this algorithm linear.
6.3272 + var limitFailedCompares = smlIndexMax * 10, failedCompares,
6.3273 + a, d, notInSmlItem, notInBigItem;
6.3274 + // Go through the items that have been added and deleted and try to find matches between them.
6.3275 + for (failedCompares = a = 0; (dontLimitMoves || failedCompares < limitFailedCompares) && (notInSmlItem = notInSml[a]); a++) {
6.3276 + for (d = 0; notInBigItem = notInBig[d]; d++) {
6.3277 + if (notInSmlItem['value'] === notInBigItem['value']) {
6.3278 + notInSmlItem['moved'] = notInBigItem['index'];
6.3279 + notInBigItem['moved'] = notInSmlItem['index'];
6.3280 + notInBig.splice(d,1); // This item is marked as moved; so remove it from notInBig list
6.3281 + failedCompares = d = 0; // Reset failed compares count because we're checking for consecutive failures
6.3282 + break;
6.3283 + }
6.3284 + }
6.3285 + failedCompares += d;
6.3286 + }
6.3287 + }
6.3288 + return editScript.reverse();
6.3289 + }
6.3290 +
6.3291 + return compareArrays;
6.3292 +})();
6.3293 +
6.3294 +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
6.3295 +
6.3296 +(function () {
6.3297 + // Objective:
6.3298 + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
6.3299 + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
6.3300 + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
6.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
6.3302 + // previously mapped - retain those nodes, and just insert/delete other ones
6.3303 +
6.3304 + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
6.3305 + // You can use this, for example, to activate bindings on those nodes.
6.3306 +
6.3307 + function fixUpNodesToBeMovedOrRemoved(contiguousNodeArray) {
6.3308 + // Before moving, deleting, or replacing a set of nodes that were previously outputted by the "map" function, we have to reconcile
6.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,
6.3310 + // or that new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
6.3311 + // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
6.3312 + // So, this function translates the old "map" output array into its best guess of what set of current DOM nodes should be removed.
6.3313 + //
6.3314 + // Rules:
6.3315 + // [A] Any leading nodes that aren't in the document any more should be ignored
6.3316 + // These most likely correspond to memoization nodes that were already removed during binding
6.3317 + // See https://github.com/SteveSanderson/knockout/pull/440
6.3318 + // [B] We want to output a contiguous series of nodes that are still in the document. So, ignore any nodes that
6.3319 + // have already been removed, and include any nodes that have been inserted among the previous collection
6.3320 +
6.3321 + // Rule [A]
6.3322 + while (contiguousNodeArray.length && !ko.utils.domNodeIsAttachedToDocument(contiguousNodeArray[0]))
6.3323 + contiguousNodeArray.splice(0, 1);
6.3324 +
6.3325 + // Rule [B]
6.3326 + if (contiguousNodeArray.length > 1) {
6.3327 + // Build up the actual new contiguous node set
6.3328 + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current];
6.3329 + while (current !== last) {
6.3330 + current = current.nextSibling;
6.3331 + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
6.3332 + return;
6.3333 + newContiguousSet.push(current);
6.3334 + }
6.3335 +
6.3336 + // ... then mutate the input array to match this.
6.3337 + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet)
6.3338 + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet));
6.3339 + }
6.3340 + return contiguousNodeArray;
6.3341 + }
6.3342 +
6.3343 + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
6.3344 + // Map this array value inside a dependentObservable so we re-map when any dependency changes
6.3345 + var mappedNodes = [];
6.3346 + var dependentObservable = ko.dependentObservable(function() {
6.3347 + var newMappedNodes = mapping(valueToMap, index) || [];
6.3348 +
6.3349 + // On subsequent evaluations, just replace the previously-inserted DOM nodes
6.3350 + if (mappedNodes.length > 0) {
6.3351 + ko.utils.replaceDomNodes(fixUpNodesToBeMovedOrRemoved(mappedNodes), newMappedNodes);
6.3352 + if (callbackAfterAddingNodes)
6.3353 + ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
6.3354 + }
6.3355 +
6.3356 + // Replace the contents of the mappedNodes array, thereby updating the record
6.3357 + // of which nodes would be deleted if valueToMap was itself later removed
6.3358 + mappedNodes.splice(0, mappedNodes.length);
6.3359 + ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
6.3360 + }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } });
6.3361 + return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
6.3362 + }
6.3363 +
6.3364 + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult";
6.3365 +
6.3366 + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
6.3367 + // Compare the provided array against the previous one
6.3368 + array = array || [];
6.3369 + options = options || {};
6.3370 + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
6.3371 + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
6.3372 + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
6.3373 + var editScript = ko.utils.compareArrays(lastArray, array);
6.3374 +
6.3375 + // Build the new mapping result
6.3376 + var newMappingResult = [];
6.3377 + var lastMappingResultIndex = 0;
6.3378 + var newMappingResultIndex = 0;
6.3379 +
6.3380 + var nodesToDelete = [];
6.3381 + var itemsToProcess = [];
6.3382 + var itemsForBeforeRemoveCallbacks = [];
6.3383 + var itemsForMoveCallbacks = [];
6.3384 + var itemsForAfterAddCallbacks = [];
6.3385 + var mapData;
6.3386 +
6.3387 + function itemMovedOrRetained(editScriptIndex, oldPosition) {
6.3388 + mapData = lastMappingResult[oldPosition];
6.3389 + if (newMappingResultIndex !== oldPosition)
6.3390 + itemsForMoveCallbacks[editScriptIndex] = mapData;
6.3391 + // Since updating the index might change the nodes, do so before calling fixUpNodesToBeMovedOrRemoved
6.3392 + mapData.indexObservable(newMappingResultIndex++);
6.3393 + fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes);
6.3394 + newMappingResult.push(mapData);
6.3395 + itemsToProcess.push(mapData);
6.3396 + }
6.3397 +
6.3398 + function callCallback(callback, items) {
6.3399 + if (callback) {
6.3400 + for (var i = 0, n = items.length; i < n; i++) {
6.3401 + if (items[i]) {
6.3402 + ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
6.3403 + callback(node, i, items[i].arrayEntry);
6.3404 + });
6.3405 + }
6.3406 + }
6.3407 + }
6.3408 + }
6.3409 +
6.3410 + for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
6.3411 + movedIndex = editScriptItem['moved'];
6.3412 + switch (editScriptItem['status']) {
6.3413 + case "deleted":
6.3414 + if (movedIndex === undefined) {
6.3415 + mapData = lastMappingResult[lastMappingResultIndex];
6.3416 +
6.3417 + // Stop tracking changes to the mapping for these nodes
6.3418 + if (mapData.dependentObservable)
6.3419 + mapData.dependentObservable.dispose();
6.3420 +
6.3421 + // Queue these nodes for later removal
6.3422 + nodesToDelete.push.apply(nodesToDelete, fixUpNodesToBeMovedOrRemoved(mapData.mappedNodes));
6.3423 + if (options['beforeRemove']) {
6.3424 + itemsForBeforeRemoveCallbacks[i] = mapData;
6.3425 + itemsToProcess.push(mapData);
6.3426 + }
6.3427 + }
6.3428 + lastMappingResultIndex++;
6.3429 + break;
6.3430 +
6.3431 + case "retained":
6.3432 + itemMovedOrRetained(i, lastMappingResultIndex++);
6.3433 + break;
6.3434 +
6.3435 + case "added":
6.3436 + if (movedIndex !== undefined) {
6.3437 + itemMovedOrRetained(i, movedIndex);
6.3438 + } else {
6.3439 + mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
6.3440 + newMappingResult.push(mapData);
6.3441 + itemsToProcess.push(mapData);
6.3442 + if (!isFirstExecution)
6.3443 + itemsForAfterAddCallbacks[i] = mapData;
6.3444 + }
6.3445 + break;
6.3446 + }
6.3447 + }
6.3448 +
6.3449 + // Call beforeMove first before any changes have been made to the DOM
6.3450 + callCallback(options['beforeMove'], itemsForMoveCallbacks);
6.3451 +
6.3452 + // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
6.3453 + ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
6.3454 +
6.3455 + // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
6.3456 + for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
6.3457 + // Get nodes for newly added items
6.3458 + if (!mapData.mappedNodes)
6.3459 + ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
6.3460 +
6.3461 + // Put nodes in the right place if they aren't there already
6.3462 + for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
6.3463 + if (node !== nextNode)
6.3464 + ko.virtualElements.insertAfter(domNode, node, lastNode);
6.3465 + }
6.3466 +
6.3467 + // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
6.3468 + if (!mapData.initialized && callbackAfterAddingNodes) {
6.3469 + callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
6.3470 + mapData.initialized = true;
6.3471 + }
6.3472 + }
6.3473 +
6.3474 + // If there's a beforeRemove callback, call it after reordering.
6.3475 + // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
6.3476 + // some sort of animation, which is why we first reorder the nodes that will be removed. If the
6.3477 + // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
6.3478 + // Perhaps we'll make that change in the future if this scenario becomes more common.
6.3479 + callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
6.3480 +
6.3481 + // Finally call afterMove and afterAdd callbacks
6.3482 + callCallback(options['afterMove'], itemsForMoveCallbacks);
6.3483 + callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
6.3484 +
6.3485 + // Store a copy of the array items we just considered so we can difference it next time
6.3486 + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
6.3487 + }
6.3488 +})();
6.3489 +
6.3490 +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
6.3491 +ko.nativeTemplateEngine = function () {
6.3492 + this['allowTemplateRewriting'] = false;
6.3493 +}
6.3494 +
6.3495 +ko.nativeTemplateEngine.prototype = new ko.templateEngine();
6.3496 +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
6.3497 + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
6.3498 + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
6.3499 + templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
6.3500 +
6.3501 + if (templateNodes) {
6.3502 + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
6.3503 + } else {
6.3504 + var templateText = templateSource['text']();
6.3505 + return ko.utils.parseHtmlFragment(templateText);
6.3506 + }
6.3507 +};
6.3508 +
6.3509 +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
6.3510 +ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
6.3511 +
6.3512 +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
6.3513 +(function() {
6.3514 + ko.jqueryTmplTemplateEngine = function () {
6.3515 + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
6.3516 + // doesn't expose a version number, so we have to infer it.
6.3517 + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
6.3518 + // which KO internally refers to as version "2", so older versions are no longer detected.
6.3519 + var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
6.3520 + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl']))
6.3521 + return 0;
6.3522 + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
6.3523 + try {
6.3524 + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
6.3525 + // Since 1.0.0pre, custom tags should append markup to an array called "__"
6.3526 + return 2; // Final version of jquery.tmpl
6.3527 + }
6.3528 + } catch(ex) { /* Apparently not the version we were looking for */ }
6.3529 +
6.3530 + return 1; // Any older version that we don't support
6.3531 + })();
6.3532 +
6.3533 + function ensureHasReferencedJQueryTemplates() {
6.3534 + if (jQueryTmplVersion < 2)
6.3535 + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
6.3536 + }
6.3537 +
6.3538 + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
6.3539 + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
6.3540 + }
6.3541 +
6.3542 + this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
6.3543 + options = options || {};
6.3544 + ensureHasReferencedJQueryTemplates();
6.3545 +
6.3546 + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
6.3547 + var precompiled = templateSource['data']('precompiled');
6.3548 + if (!precompiled) {
6.3549 + var templateText = templateSource['text']() || "";
6.3550 + // Wrap in "with($whatever.koBindingContext) { ... }"
6.3551 + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
6.3552 +
6.3553 + precompiled = jQuery['template'](null, templateText);
6.3554 + templateSource['data']('precompiled', precompiled);
6.3555 + }
6.3556 +
6.3557 + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
6.3558 + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
6.3559 +
6.3560 + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
6.3561 + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
6.3562 +
6.3563 + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
6.3564 + return resultNodes;
6.3565 + };
6.3566 +
6.3567 + this['createJavaScriptEvaluatorBlock'] = function(script) {
6.3568 + return "{{ko_code ((function() { return " + script + " })()) }}";
6.3569 + };
6.3570 +
6.3571 + this['addTemplate'] = function(templateName, templateMarkup) {
6.3572 + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>");
6.3573 + };
6.3574 +
6.3575 + if (jQueryTmplVersion > 0) {
6.3576 + jQuery['tmpl']['tag']['ko_code'] = {
6.3577 + open: "__.push($1 || '');"
6.3578 + };
6.3579 + jQuery['tmpl']['tag']['ko_with'] = {
6.3580 + open: "with($1) {",
6.3581 + close: "} "
6.3582 + };
6.3583 + }
6.3584 + };
6.3585 +
6.3586 + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
6.3587 +
6.3588 + // Use this one by default *only if jquery.tmpl is referenced*
6.3589 + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
6.3590 + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
6.3591 + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
6.3592 +
6.3593 + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
6.3594 +})();
6.3595 +});
6.3596 +})(window,document,navigator,window["jQuery"]);
6.3597 +})();
6.3598 \ No newline at end of file
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/ko-fx/src/test/java/org/apidesign/html/kofx/KnockoutFXTest.java Thu Apr 25 16:21:50 2013 +0200
7.3 @@ -0,0 +1,80 @@
7.4 +/**
7.5 + * HTML via Java(tm) Language Bindings
7.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
7.7 + *
7.8 + * This program is free software: you can redistribute it and/or modify
7.9 + * it under the terms of the GNU General Public License as published by
7.10 + * the Free Software Foundation, version 2 of the License.
7.11 + *
7.12 + * This program is distributed in the hope that it will be useful,
7.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
7.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7.15 + * GNU General Public License for more details. apidesign.org
7.16 + * designates this particular file as subject to the
7.17 + * "Classpath" exception as provided by apidesign.org
7.18 + * in the License file that accompanied this code.
7.19 + *
7.20 + * You should have received a copy of the GNU General Public License
7.21 + * along with this program. Look for COPYING file in the top folder.
7.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
7.23 + */
7.24 +package org.apidesign.html.kofx;
7.25 +
7.26 +import java.util.Map;
7.27 +import net.java.html.json.Context;
7.28 +import netscape.javascript.JSObject;
7.29 +import org.apidesign.bck2brwsr.vmtest.VMTest;
7.30 +import org.apidesign.html.json.spi.ContextBuilder;
7.31 +import org.apidesign.html.json.tck.KnockoutTCK;
7.32 +import org.json.JSONException;
7.33 +import org.json.JSONObject;
7.34 +import org.openide.util.lookup.ServiceProvider;
7.35 +import org.testng.annotations.Factory;
7.36 +
7.37 +/**
7.38 + *
7.39 + * @author Jaroslav Tulach <jtulach@netbeans.org>
7.40 + */
7.41 +@ServiceProvider(service = KnockoutTCK.class)
7.42 +public final class KnockoutFXTest extends KnockoutTCK {
7.43 + public KnockoutFXTest() {
7.44 + }
7.45 +
7.46 + @Factory public static Object[] compatibilityTests() {
7.47 + System.setProperty("vmtest.brwsrs", "fx");
7.48 + return VMTest.create(testClasses());
7.49 + }
7.50 +
7.51 + @Override
7.52 + public Context createContext() {
7.53 + FXContext fx = new FXContext();
7.54 + return ContextBuilder.create().
7.55 + withTechnology(fx).withTransfer(fx).build();
7.56 + }
7.57 +
7.58 + @Override
7.59 + public Object createJSON(Map<String, Object> values) {
7.60 + JSONObject json = new JSONObject();
7.61 + for (Map.Entry<String, Object> entry : values.entrySet()) {
7.62 + try {
7.63 + json.put(entry.getKey(), entry.getValue());
7.64 + } catch (JSONException ex) {
7.65 + throw new IllegalStateException(ex);
7.66 + }
7.67 + }
7.68 + return json;
7.69 + }
7.70 +
7.71 + private static JSObject eval;
7.72 + @Override
7.73 + public Object executeScript(String script, Object[] arguments) {
7.74 + if (eval == null) {
7.75 + eval = (JSObject) Knockout.web().executeScript("(function(scope) {"
7.76 + + " scope.jko = {};"
7.77 + + " scope.jko.compute = function(s, args) { var f = new Function(s); return f.apply(null, args); }"
7.78 + + "})(window); window.jko;");
7.79 + }
7.80 + return eval.call("compute", script, arguments);
7.81 + }
7.82 +
7.83 +}
8.1 --- a/pom.xml Thu Apr 25 12:40:29 2013 +0200
8.2 +++ b/pom.xml Thu Apr 25 16:21:50 2013 +0200
8.3 @@ -19,6 +19,7 @@
8.4 <modules>
8.5 <module>json</module>
8.6 <module>json-tck</module>
8.7 + <module>ko-fx</module>
8.8 </modules>
8.9 <licenses>
8.10 <license>
8.11 @@ -80,6 +81,7 @@
8.12 <excludes>
8.13 <exclude>*</exclude>
8.14 <exclude>.*/**</exclude>
8.15 + <exclude>ko-fx/src/main/resources/org/apidesign/html/kofx/knockout*.js</exclude>
8.16 </excludes>
8.17 </configuration>
8.18 </plugin>