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 Object koData() {
73 private static final JSObject KObject;
75 KObject = (JSObject) web().executeScript(
78 + " scope.KObject = {};"
79 + " scope.KObject.create= function(value) {"
80 + " var cnt = ++kCnt;"
82 + " ret.toString = function() { return 'KObject' + cnt + ' value: ' + value + ' props: ' + Object.keys(this); };"
85 + " scope.KObject.array= function() {"
86 + " return Array.prototype.slice.call(arguments);"
88 + "})(window); window.KObject"
92 static Object toArray(Object[] arr) {
93 return KObject.call("array", arr);
96 public static <M> Knockout applyBindings(
97 Object model, String[] propsGettersAndSetters,
98 String[] methodsAndSignatures
100 Object bindings = KObject.call("create", model);
101 applyImpl(propsGettersAndSetters, model.getClass(), bindings, model, methodsAndSignatures);
102 return new Knockout(bindings);
104 public static <M> Knockout applyBindings(
105 Class<M> modelClass, M model, String[] propsGettersAndSetters,
106 String[] methodsAndSignatures
108 Object bindings = next;
110 if (bindings == null) {
111 bindings = KObject.call("create", model);
113 applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
114 applyBindings(bindings);
115 return new Knockout(bindings);
118 public void valueHasMutated(String prop) {
119 LOG.log(Level.INFO, "property mutated: {0}", prop);
121 JSObject koProp = (JSObject) ((JSObject) model).getMember(prop);
122 koProp.call("valueHasMutated");
123 } catch (Throwable t) {
124 LOG.log(Level.WARNING, "valueHasMutated failed for {0}", model);
129 @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
130 public static void triggerEvent(String id, String ev) {
133 @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
135 + " 'read': function() {\n"
136 + " var v = model[getter]();\n"
137 + " if (array) v = v.koArray();\n"
140 + " 'owner': bindings\n"
142 + "if (setter != null) {\n"
143 + " bnd['write'] = function(val) {\n"
144 + " model[setter](primitive ? new Number(val) : val);\n"
147 + "bindings[prop] = ko['computed'](bnd);"
149 private static void bind(
150 Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
153 JSObject bnd = (JSObject) e.executeScript("var x = {}; x.bnd = "
154 + "new Function('ko', 'bindings', 'model', 'prop', 'getter', 'setter', 'primitive', 'array', '"
156 + " read: function() {"
158 + " var v = model[getter]();"
159 + " console.log(\" getter value \" + v + \" for property \" + prop);"
160 + " try { v = v.koData(); } catch (ignore) {"
161 + " console.log(\"Cannot convert to koData: \" + ignore);"
163 + " console.log(\" getter ret value \" + v);"
164 + " for (var pn in v) {"
165 + " console.log(\" prop: \" + pn + \" + in + \" + v + \" = \" + v[pn]);"
166 + " if (typeof v[pn] == \"function\") console.log(\" its function value:\" + v[pn]());"
168 + " console.log(\" all props printed for \" + (typeof v));"
171 + " alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
174 + " owner: bindings,"
175 + " deferEvaluation: true"
177 + "if (setter != null) {"
178 + " bnd.write = function(val) {"
179 + " model[setter](primitive ? new Number(val) : val);"
182 + "bindings[prop] = ko.computed(bnd);'"
185 Object ko = e.executeScript("ko");
187 KOProperty kop = new KOProperty(model, strip(getter), strip(setter));
188 bnd.call("bnd", ko, bindings, kop, prop, "get", "set", primitive, array);
189 LOG.log(Level.INFO, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
190 } catch (Throwable ex) {
191 LOG.log(Level.INFO, "binding failed for {0} on {1}", new Object[]{prop, bindings});
195 private static String strip(String mangled) {
196 if (mangled == null) {
199 int under = mangled.indexOf("__");
200 return mangled.substring(0, under);
202 @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body =
203 "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
205 private static void expose(
206 Object bindings, Object model, String prop, String sig
210 @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
211 private static void applyBindings(Object bindings) {
212 JSObject ko = (JSObject) web().executeScript("ko");
213 ko.call("applyBindings", bindings);
216 private static WebEngine web() {
217 return (WebEngine) System.getProperties().get("webEngine");
221 private static void applyImpl(
222 String[] propsGettersAndSetters,
226 String[] methodsAndSignatures
227 ) throws IllegalStateException, SecurityException {
228 for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
230 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
231 bind(bindings, model, propsGettersAndSetters[i],
232 propsGettersAndSetters[i + 1],
233 propsGettersAndSetters[i + 2],
234 getter.getReturnType().isPrimitive(),
235 List.class.isAssignableFrom(getter.getReturnType()));
236 } catch (NoSuchMethodException ex) {
237 throw new IllegalStateException(ex.getMessage());
240 for (int i = 0; i < methodsAndSignatures.length; i += 2) {
242 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);