2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.bck2brwsr.htmlpage;
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStreamReader;
23 import java.lang.reflect.Method;
24 import java.util.List;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27 import javafx.scene.web.WebEngine;
28 import netscape.javascript.JSObject;
29 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
32 /** Provides binding between models and
34 * @author Jaroslav Tulach <jtulach@netbeans.org>
36 @ExtraJavaScript(resource = "/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js")
37 public class Knockout {
38 private static final Logger LOG = Logger.getLogger(Knockout.class.getName());
41 private final Object model;
44 BufferedReader r = new BufferedReader(new InputStreamReader(Knockout.class.getResourceAsStream("knockout-2.2.1.js")));
45 StringBuilder sb = new StringBuilder();
48 String l = r.readLine();
52 sb.append(l).append('\n');
53 } catch (IOException ex) {
54 throw new IllegalStateException(ex);
57 web().executeScript(sb.toString());
58 Object ko = web().executeScript("ko");
59 assert ko != null : "Knockout library successfully defined 'ko'";
61 Console.register(web());
65 Knockout(Object model) {
66 this.model = model == null ? this : model;
69 public static <M> Knockout applyBindings(
70 Object model, String[] propsGettersAndSetters,
71 String[] methodsAndSignatures
73 applyImpl(propsGettersAndSetters, model.getClass(), model, model, methodsAndSignatures);
74 return new Knockout(model);
76 public static <M> Knockout applyBindings(
77 Class<M> modelClass, M model, String[] propsGettersAndSetters,
78 String[] methodsAndSignatures
80 Object bindings = next;
82 if (bindings == null) {
83 bindings = web().executeScript("new Object()");
85 applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
86 applyBindings(bindings);
87 return new Knockout(bindings);
90 public void valueHasMutated(String prop) {
91 LOG.log(Level.FINE, "property mutated: {0}", prop);
92 JSObject koProp = (JSObject) ((JSObject)model).getMember(prop);
93 koProp.call("valueHasMutated");
97 @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
98 public static void triggerEvent(String id, String ev) {
101 @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
103 + " 'read': function() {\n"
104 + " var v = model[getter]();\n"
105 + " if (array) v = v.koArray();\n"
108 + " 'owner': bindings\n"
110 + "if (setter != null) {\n"
111 + " bnd['write'] = function(val) {\n"
112 + " model[setter](primitive ? new Number(val) : val);\n"
115 + "bindings[prop] = ko['computed'](bnd);"
117 private static void bind(
118 Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
121 JSObject bnd = (JSObject) e.executeScript("var x = {}; x.bnd = "
122 + "new Function('ko', 'bindings', 'model', 'prop', 'getter', 'setter', 'primitive', 'array', '"
124 + " read: function() {"
126 + " var v = model[getter]();"
127 + " try { v = v.koData(); } catch (ignore) {};"
130 + " alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
135 + "if (setter != null) {"
136 + " bnd.write = function(val) {"
137 + " model[setter](primitive ? new Number(val) : val);"
140 + "bindings[prop] = ko.computed(bnd);'"
143 Object ko = e.executeScript("ko");
144 bnd.call("bnd", ko, bindings, model, prop, strip(getter), strip(setter), primitive, array);
145 LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
148 private static String strip(String mangled) {
149 if (mangled == null) {
152 int under = mangled.indexOf("__");
153 return mangled.substring(0, under);
155 @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
156 "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
158 private static void expose(
159 Object bindings, Object model, String prop, String sig
163 @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
164 private static void applyBindings(Object bindings) {
165 JSObject ko = (JSObject) web().executeScript("ko");
166 ko.call("applyBindings", bindings);
169 private static WebEngine web() {
170 return (WebEngine) System.getProperties().get("webEngine");
174 private static void applyImpl(
175 String[] propsGettersAndSetters,
179 String[] methodsAndSignatures
180 ) throws IllegalStateException, SecurityException {
181 for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
183 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
184 bind(bindings, model, propsGettersAndSetters[i],
185 propsGettersAndSetters[i + 1],
186 propsGettersAndSetters[i + 2],
187 getter.getReturnType().isPrimitive(),
188 List.class.isAssignableFrom(getter.getReturnType()));
189 } catch (NoSuchMethodException ex) {
190 throw new IllegalStateException(ex.getMessage());
193 for (int i = 0; i < methodsAndSignatures.length; i += 2) {
195 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);