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);
93 JSObject koProp = (JSObject) ((JSObject) model).getMember(prop);
94 koProp.call("valueHasMutated");
95 } catch (Throwable t) {
96 LOG.log(Level.FINE, "valueHasMutated failed for {0}", model);
101 @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
102 public static void triggerEvent(String id, String ev) {
105 @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
107 + " 'read': function() {\n"
108 + " var v = model[getter]();\n"
109 + " if (array) v = v.koArray();\n"
112 + " 'owner': bindings\n"
114 + "if (setter != null) {\n"
115 + " bnd['write'] = function(val) {\n"
116 + " model[setter](primitive ? new Number(val) : val);\n"
119 + "bindings[prop] = ko['computed'](bnd);"
121 private static void bind(
122 Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
125 JSObject bnd = (JSObject) e.executeScript("var x = {}; x.bnd = "
126 + "new Function('ko', 'bindings', 'model', 'prop', 'getter', 'setter', 'primitive', 'array', '"
128 + " read: function() {"
130 + " var v = model[getter]();"
131 + " try { v = v.koData(); } catch (ignore) {};"
134 + " alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
139 + "if (setter != null) {"
140 + " bnd.write = function(val) {"
141 + " model[setter](primitive ? new Number(val) : val);"
144 + "bindings[prop] = ko.computed(bnd);'"
147 Object ko = e.executeScript("ko");
149 bnd.call("bnd", ko, bindings, model, prop, strip(getter), strip(setter), primitive, array);
150 LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
151 } catch (Throwable ex) {
152 LOG.log(Level.FINE, "binding failed for {0} on {1}", new Object[]{prop, bindings});
156 private static String strip(String mangled) {
157 if (mangled == null) {
160 int under = mangled.indexOf("__");
161 return mangled.substring(0, under);
163 @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
164 "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
166 private static void expose(
167 Object bindings, Object model, String prop, String sig
171 @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
172 private static void applyBindings(Object bindings) {
173 JSObject ko = (JSObject) web().executeScript("ko");
174 ko.call("applyBindings", bindings);
177 private static WebEngine web() {
178 return (WebEngine) System.getProperties().get("webEngine");
182 private static void applyImpl(
183 String[] propsGettersAndSetters,
187 String[] methodsAndSignatures
188 ) throws IllegalStateException, SecurityException {
189 for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
191 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
192 bind(bindings, model, propsGettersAndSetters[i],
193 propsGettersAndSetters[i + 1],
194 propsGettersAndSetters[i + 2],
195 getter.getReturnType().isPrimitive(),
196 List.class.isAssignableFrom(getter.getReturnType()));
197 } catch (NoSuchMethodException ex) {
198 throw new IllegalStateException(ex.getMessage());
201 for (int i = 0; i < methodsAndSignatures.length; i += 2) {
203 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);