Calling JavaScript from Flex with External Interface
The Flex Ajax Bridge, which for some reason you can only download with Flex Data Services (a 150mb+ download for a 16k file), isn’t the only way to send data from Flex to JavaScript there’s also the External Interface API. I’m working on a Rails project tracker application for a construction company and need to set start and end dates for each project. To make sure dates are entered without mistakes I needed a calendar widget that I could easily drop in a form and customize. I tried out some of the Ajax libraries calendars but they where either a) hard to figure out or b) hard to customize or c) both.
I was worried the Flex solution would be a large file at 152k but was surprised to find the files needed for the best Ajax Calendar I found, the Yahoo! UI one, were double in size at 292k (js, css, and gifs). You can download the source here.

Here’s the MXML code to layout the calendars:
Here’s the ActionScript to validate the dates and send the data to JavaScript. ExternallInterface.call() is the method that sends the data:
import flash.external.*;
import mx.controls.Alert;
public var startDate_reset:Date = undefined;
public var endDate_reset:Date = undefined;
public : void
{
// start date
if (calendar.id == "startDate")
{
if (endDate.enabled && endDate.selectedDate <= startDate.selectedDate)
{
Alert.show("Start Date must be before End Date");
startDate.selectedDate = startDate_reset;
}
else
{
endDate.enabled = true;
startDate_reset = startDate.selectedDate;
setDateJS(calendar);
}
}
// end date
else
{
if (endDate.selectedDate <= startDate.selectedDate)
{
Alert.show("End Date must be after Start Date");
endDate.selectedDate = endDate_reset;
}
else
{
endDate_reset = endDate.selectedDate;
setDateJS(calendar);
}
}
}
public : void
{
var s:String;
if (ExternalInterface.available)
{
var eventObj:Object = new Object();
eventObj.id = calendar.id;
eventObj.date = calendar.selectedDate;
var wrapperFunction:String = "setDate";
s = ExternalInterface.call(wrapperFunction, eventObj);
}
else
{
s = "Wrapper not available";
}
}
And finally the JavaScript and markup on the page, Prototype is used to set the input values (they have ids to match their Flex counterparts):
Flex to JavaScript, Calendar Example
Start Date:
End Date:




Like this post? subscribe to the feed.






[…] My Flex DateChooser to JavaScript example didn’t solve my date selection problem entirely as the project I’m working on requires a project to have a start week rather than a start day. The Flex DateChooser has built in selectable ranges so it’s pretty easy to set that up (right click on swf to view source). […]
Pingback by Vixiom Axioms » Flex DateChooser select a week — May 14, 2007 @ 5:05 pm
good
Comment by atar — August 11, 2008 @ 4:03 pm