Comments
bruce.armstrong wrote: Somebody just said it better than I did, and with more chops to say it: Open Letter to Mark Zuckerberg, Sheryl Sandberg & Facebook Mobile
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Closures in Compiled JavaFX Script
One of the very useful (and cool) features of compiled JavaFX Script will be closures

From Jim Weaver's Learn JavaFX Weblog

One of the very useful (and cool) features of compiled JavaFX Script will be closures.  In a nutshell, JavaFX Script closures provide the ability to define a function within another function with the inner function having access to the local variables of the outer function.  This feature is enabled by the fact that in compiled JavaFX Script, functions are first-class objects, which provides the ability to assign functions to variables and to pass functions as arguments to other functions.  You can read more about closures in this Wikipedia article.

Closures are often used to implement callback functions, many times handling UI events.  Since the UI part of compiled JavaFX Script isn't ready for prime-time yet, I'd like to show you a callback example in which a function is called when a timer expires.  You can run this example by downloading and building the JavaFX Compiler in its current state from the Subversion repository in the OpenJFX Compiler Project

Here's the source code for the example:

/*
*  ClosureExample.fx - Demonstrates closures, and that
* functions are first-class
*  objects in compiled JavaFX Script.
*
*  Uses JavaFX Script compiled version
*  Developed 2007 by James L. Weaver
* (jim.weaver at lat-inc dot com)
*/

import java.lang.System;
import java.lang.Thread;

public class ClosureExample {

  function startTimer(millis:Integer,
wakeUp:function():Void):Void {
    Thread.currentThread().sleep(millis);
    wakeUp();
  }
 
  function setAlarm(sleepTime:Integer):Void {
    var message = "Time to wake up!";
    var wakeUpFunc =
      function() {
        System.out.println(message);
        System.out.println("You slept
for {sleepTime} milliseconds");
      };
    startTimer(sleepTime, wakeUpFunc);
   
  }
}

var example =
  ClosureExample {
  };
 
example.setAlarm(3000);

Walking Through the Closure Related Features of this Example

After creating an instance of the ClosureExample class, and calling its setAlarm() function, you'll notice that an anonymous function is defined and assigned to a variable named wakeUpFunc.  After that, the startTimer() function is invoked, passing the desired duration of the timer, as well as the wakeUpFunc reference.

Within the startTimer() function, the sleep() method of the Java Thread class is called, which causes the current thread to sleep for the desired number of milliseconds.  This, by the way, demonstrates JavaFX Script's ability to leverage the power of Java classes (see the Putting My CTO Hat On post).  After the thread wakes up, the callback function that was passed into the startTimer() function is invoked, which performs the closure.

The net effect is that the callback function accesses and prints the values of local variables of the setAlarm() function.  The closure feature allows access to these variables from within the scope of the callback function, even though they're not local to the callback function.

About James L. Weaver
James L. (Jim) Weaver is founder and president of jMentor, formed in 2000 to provide Java programming-related training to companies and individuals. He has served as a system architect and developer for over 25 years, specializing in leading-edge software development. His specialties include Java, object-oriented, and web-based technologies. He has authored books on the Java programming language, including most recently JavaFX Script, published by Apress.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

I actually stumbled on this article as I was searching about JavaFX because someone mentioned that JavaFX didn't support inner functions. In my googling I came across this. Good to see that isn't the case. Thanks for the list and link. We haven't had a need for JavaFX yet, but I always like to keep the language option open. Thanks!

Aaron,
Good to hear from you. It's interesting that you would respond to this particular post, as I recall that you first introduced closures to me (in the context of JavaScript). The major benefits that I see with JavaFX Script are:

* declaratively expressing the UI, including layout widgets

* binding the UI to a model, and its innate ability to do the MVC pattern

* attribute triggers

* leveraging Java classes and compiling to JVM
bytecode

* excellent 2D graphics, and soon to come animation, support. 3D graphics will follow.

All of the above are implemented in a simple, elegant, and fun to use way. Please see my [http://learnjavafx.typepad.com/weblog/2007/10/putting-my-cto-.html Putting My CTO Hat On] post for more details on my rationale for utilizing JavaFX Script.

Thanks,
Jim Weaver
"Helping You Become a JavaFXpert" weblog:
http://javafxpert.com

Nice article. I'm just starting to look at JavaFX and want to know the benefits of use it verse something like Rhino. It seems that Rhino offers many of the same capabilities (using native java classes) and is already integrated with some projects, like Apache Cocoon. Rhino being JavaScript, I am more familiar with it. Other than JavaFX being strongly typed, what other benefits does JavaFX provide?


Your Feedback
Aaron Romine wrote: I actually stumbled on this article as I was searching about JavaFX because someone mentioned that JavaFX didn't support inner functions. In my googling I came across this. Good to see that isn't the case. Thanks for the list and link. We haven't had a need for JavaFX yet, but I always like to keep the language option open. Thanks!
Jim Weaver wrote: Aaron, Good to hear from you. It's interesting that you would respond to this particular post, as I recall that you first introduced closures to me (in the context of JavaScript). The major benefits that I see with JavaFX Script are: * declaratively expressing the UI, including layout widgets * binding the UI to a model, and its innate ability to do the MVC pattern * attribute triggers * leveraging Java classes and compiling to JVM bytecode * excellent 2D graphics, and soon to come animation, support. 3D graphics will follow. All of the above are implemented in a simple, elegant, and fun to use way. Please see my [http://learnjavafx.typepad.com/weblog/2007/10/putting-my-cto-.html Putting My CTO Hat On] post for more details on my rationale for utilizing JavaFX Script. Thanks, Jim Weaver "Helping You Become a JavaFXpert" weblog: http://javafxpert.com
Aaron Romine wrote: Nice article. I'm just starting to look at JavaFX and want to know the benefits of use it verse something like Rhino. It seems that Rhino offers many of the same capabilities (using native java classes) and is already integrated with some projects, like Apache Cocoon. Rhino being JavaScript, I am more familiar with it. Other than JavaFX being strongly typed, what other benefits does JavaFX provide?
Enterprise Open Source Magazine Latest Stories . . .
Before embarking on using open source cloud technology for your web property, a basic understanding of cloud, as it’s used in the industry, is essential. While there might be exceptions, here are the definitions. A software application delivered on the web instead of installing standa...
Businesses today generate billions of events or 100s of TBs of data in a month. These data contain valuable insights into customer behavior, key trends, buying patterns, etc. If these are successfully mined, they can lead to successful decision-making to maximize revenue and traffic fo...
Grid Dynamics, an eCommerce technology solutions company, and GridGain Systems, makers of an open source in-memory platform for Big Data processing, on Wednesday announced the expansion of their partnership which began in 2008. Grid Dynamics provides personalization and big data solut...
Private clouds solve many problems for enterprises and bring unique operational challenges along with them. There are dozens of companies of all sizes that will build you a private cloud and turn over the keys – then what? Trying to convert a traditional enterprise IT operations team t...
The networking industry has gone through different waves over last 30+ years. In the ’80s, the first wave was all about connecting and sharing; how to connect a computer to other peripheral devices and other computers. There were many players who developed technology and services to ad...
If your organization already uses virtualized infrastructure, you are well on your way to providing IT as a Service. But as businesses demand faster results in today’s competitive market, organizations look to gain more benefits from cloud computing than just virtualized infrastructure...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE