Flex – controlling parent page by Javascript using ExternalInterface

When developing a Flex application you are generally involved with the nitty gritty coding, getting your text boxes looking right; hooking up that button and making sure your webservices are behaving. Something you probably haven’t started to consider is that the SWF you end up with is going to have to live on a page somewhere. When you get closer to release time, suddenly your thoughts turn to integrating your application with an actual webpage.

A very useful trick to be aware of is that your Flex application can control its parent page to a certain extent by executing Javascript on it. So for example, at graffed.com you’ll notice that instead of showing the Flex application straight away, we show a basic loading image in HTML and then once the entire app has loaded, we switch the loading image to a button to launch the app.

Loading the app

Loading the app

Loading completed

Loading completed


This way, visitors are shown a landing page which loads very quickly that they can read through, and the application is loaded in the background. Once the application is loaded, the parent page displays a nice button for them to launch. It’s also good for SEO since the parent page is what the search engines will see, rather than a blank page with a Flex application.

To achieve this magic, we use ExternalInterface to interact with the parent page. First off, create an appropriate Javascript function within your parent page for the Flex app to call, let’s say it’s called flexLoaded(). To call this Javascript method in your Flex application, you simply put:

ExternalInterface.call("flexLoaded");

Exceptionally easy and a very powerful way to influence the page your SWF resides in. Don’t forget to import the appropriate library at the top of the Actionscript, i.e

import flash.external.*;

Flex – extra unbound custom parameters in a webservice

One of the greatest parts of Flex is the ease of integration to other servers. As a client side technology, Flex is clearly designed to embrace communication between itself and external servers and not make the programmer jump through hoops to get there. To that end it has the component mx:HTTPService, they can literally be defined in the XML components of your MXML document. That is seriously trivial, close to as easy as writing a tag in an HTML document. Forget worrying about establishing connections, sending data and processing the data returned. Typically, the values sent by the web service are tied to components in the document, e.g. say we have a webservice which sends the value of a textbox called myTextBox to the url http://myserver.com/myurl:

<mx:Script>
    <![CDATA[

        import mx.controls.Alert;
        import mx.rpc.events.ResultEvent;

        private function handleReturn(event:ResultEvent):void
        {
            Alert.show("returned from the webservice");
        }

        private function send():void
        {
            myWebServiceName.send();
        }

    ]]>
</mx:Script>

<mx:HTTPService
    id="myWebServiceName"
    url="http://myserver.com/myurl"
    contentType="application/xml"
    resultFormat="e4x"
    method="POST"
    result="handleReturn(event)">
    <mx:request>
        <sentdata>
            <text>{myTextBox.text}</text>
        </sentdata>
    </mx:request>
</mx:HTTPService>

<mx:TextInput id="myTextBox" />

Here the method send() will invoke the webservice with the up to date textbox data, parse the returned data as XML and call the callback method handleReturn. Great. But what if we want to attach data which is not so easily bindable, say the property of an object defined in your actionscript. Then we just need to set it on the webservice before calling .send(). For example say you had an global ActionScript object user with a public property called id which you needed to send with the request as user_id:

private function send():void
{
    myWebService.sentdata.user_id = user.id;
    myWebServiceName.send();
}

Note that sentdata is just the name of the top level XML node I include all the sent data under, it could be anything of your choosing. Because of the slight slackness of object structure in Flex and Actionscript, you can define the dynamic XML structure on the fly with myWebService.MYTOPNODE.MYNODE = DATA where MYTOPNODE, MYNODE and DATA are all what you need. Good stuff.

Flex application initialisation code using creationComplete

This is only a very small post, but something I initially struggled to find so I have deemed it worthy.

Compared to traditional UI coding, Flex hides the application flow entirely away from the programmer. You don’t need to worry about initialising the window objects, you don’t need to know about the event processing thread and you should not be concerned with how your components get drawn. All in all that is a fantastic thing. But I initially struggled to determine how to run some code once a Flex application has been loaded. For example in my latest (and soon to be posted about) project graffed, on initialisation I wanted to load the user details if they were cookied. It’s actually extremely easy, in your top level MXML mx:Application tag, simply add the attribute creationComplete=”init()”. Here init() refers to a function within the script data of the MXML file, e.g.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
    <mx:Script>
        <![CDATA[
        import mx.controls.Alert;

        private function init():void
        {
            Alert.show("Starting the program"):
        }
        ]]>
    </mx:Script>
</mx:Application>

Here, the program will run init() on launch and give you a nice informative message. Simple.

Hello World

And yes I do mean that in the geeky sense.

Who?

Welcome, my name is Daniel and I’ll be your guide for this journey, please keep hands and feet within the vehicle at all times.

So, another blog added to the (ugh!) blogosphere. Could there be anything left to say out there, any unique sentences left to be uttered? I’m sure there are plenty of combinations of words left to be spewed forth. To rephrase, are there any worthwhile sentences left to utter? My inner cynic says no but my literary heart says yes so let’s go with that for now.

What?

I’m a programmer by trade and by passion. I found myself consuming lots of material from the web for years and thought maybe now was the time to give something back. Plus I love hearing (and second best reading) the sound of my own voice. So the best of both worlds really. My craft has until recently focused solely on Java based websites. Fairly complicated sites to be fair, I currently run the tech team for the best looking business directory out there bview, and worked for the insurance comparison website simplybusiness (Phil the SEO man made me give him a link I swear).

This was honestly the first pickup that came up

This was honestly the first pickup that came up

But for fun in my spare time I’ve been focusing on the newer languages out there, Ruby On Rails (hereby RoR) being the main one. For a man who wouldn’t touch a language without a compiler (and ideally a virtual machine to run it in) I’ve branched out into the wonderful world of scripted languages. And decided for some things, I like it. My first foray was the whimsical (and occasionally NSFW) the pickuptruck, an answer looking for a question. It’s actually a great Twitter powered, user generated Web 2.0 extravaganza for pickup lines. I’ve even branched further into Flex, the dark programmer’s Flash tool with XML and everything! I’ll shortly be reporting on the app for that, needless to say it’s pretty “flash”.

Why?

I’m hoping this site becomes a useful resource for people to pick up advice on whatever technology I happen to be using this week. And a place for me to vent my spleen, my doctor said I should get the hosting on prescription to reduce my blood pressure.

As to the name of this blog, there are deep seated psychological reasons for it and I will be using my posts to exorcise demons and hopefully one day reveal the truth.