Griffon: Calling application methods from JavaScript - No Fluff Just Stuff

Griffon: Calling application methods from JavaScript

Posted by: Andres Almiray on July 12, 2013

Recently a question was raised at StackOverflow regarding the interaction of a Griffon based applet and JavaScript functions. Basically the question is: from JavaScript, how can I call methods on the applet, say a controller action? As it turns out the answer is simple: you must provide a custom Applet class that exposes what you want to call from JavaScript. Here's how to do it.

I'm using the following setup just in case you'd like to follow along

------------------------------------------------------------
  Griffon 1.3.0
------------------------------------------------------------

   Build: 12-May-2013 08:43 AM
  Groovy: 2.1.3
     Ant: 1.9.0
   Slf4j: 1.7.3
  Spring: 3.2.2.RELEASE
     JVM: 1.7.0_25 (Oracle Corporation 23.25-b01)
      OS: Mac OS X 10.7.5 x86_64

This will be a trivial Swing based calculator app just so we don't get distracted by other details however the recipe will also work for JavaFX based applets (provided you subclass the right class). The first step is then creating the app by issuing the following command

$ griffon create-app calculator

Good. We'll modify all members of the default MVC group created by the previous step. First the model

griffon-app/models/calculator/CalculatorModel.groovy

For this simple calculator we define 2 properties for storing numbers and a third property that will hold the result of applying an arithmetic operation on those two properties. Next comes the controller, where we'll see how those properties are put to good use

griffon-app/controllers/calculator/CalculatorController.groovy

Next comes the View which is nothing more than a grid form of non-editable textfields bound to the model's properties. We make them non-editable in order to avoid cheating, that is, you can't manually change the values of the textfields. Also there's no button to activate the controller action. We'll do that from JavaScript remember? Here's the View

griffon-app/views/calculator/CalculatorView.groovy

So far so good. Now comes the tricky part: we must create our own applet subclass. We'll do this by extending griffon.swing.SwingApplet, the base applet class provided by the Swing plugin.

src/main/calculator/CalculatorApplet.java

This applet exposes a single method named calculateFromJava() which will be called from the outside world. There are a few ways to grab hold of MVC members, shown here is one of the simplest. Notice the method returns the result of the computation that was calculated by the controller and set on the model. Now all that needs to be done is tweak the HTML page generated by the package command. Look up griffon-app/conf/dist/webstart/applet.html and update it with the following contents