Action Script

June 04, 2008

Displaying Character Codes in Flex

If you are capturing keyboard events and want to display the Character Code as Text all you need to do is use String.fromCharCode( …charCodes ) as in the following:

private function  keyDownHandler(event:KeyboardEvent):void

{

textInput.text = String.fromCharCode( event.keyCode );

}

 

Don’t you just love searching and searching for something that should be real simple and then feel like this:

 

Punch

 

May 15, 2008

Overloaded Methods in Action Script ( sorta )

via wikipedia

Method overloading is a feature found in various programming languages such as Ada, C#, C++ and Java that allows the creation of several functions with the same name which differ from each other in terms of the type of the input and the type of the output of the function.

I’ve wanted overloaded methods in Action Script for some time now. After using it in other languages like java and c# it’s really easy to train your mind to solve one off scenarios with overloaded methods. Much more than an easy way to provide defaults for lots of different scenarios I enjoy crafting them to manipulate program behavior for base or core classes so that the actual implementation of the program becomes much more simple and easier to maintain.

I’ve tried several approaches to getting something similar and elegant in Action Script. Most everything came down to being a hack and turned out to be more work than was necessary to implement. I know overloading is more of an AS thing than an FB thing but thinking about new FB4 features  – (my comment is still awaiting approval as of this writing, I mentioned visual studio’s intellisense, oops) the other day made me decide to sit down and attempt overloaded methods one more time. This time I wanted to look at my prominent use cases and see if there was a way to solve this issue.

The two use cases I came across time and time again were 1) eventHandler methods that accept related and similar events: breaking them out to thier own function is do-able but is a lot of work when the difference of how you handle them is 1–off. And 2) methods that take a UIComponent of some sort that either gets or sets data. For example, if you were to loop over an array of form input controls reading / writing data to them you’d find the difference in how you set or get data on them is very similar but just a little different. A TextInput just reads and writes to the “text” property. A ComboBox might read and write to a selectedItem[”property”] value. Or you might want to pull the htmlText value off the RTE.

With those use cases in mind, I thought about how I could handle the two problems simply and elegantly, not necessarily by overloaded methods but just something that could slim my code down, drop a lot of casting, and at the very least make my code more maintainable and more precise in it’s intent.

The first obvious thing I saw was that I didn’t need to worry about the number of arguments, although the technique I’m gonna demonstrate can be used with multiple parameters or event the …rest params. In my case I’m handling an event or a view in both cases. The second thing I saw was that I’d almost solved this problem. In most of these methods I was just accepting either an Event or UIComponent or something similar. The next thing I noticed was that I was either casting from within switches or if statements and I was executing my computing goal from within my function or calling an outside function to accomplish something. With that in mind I decided calling an outside function was the best method. Indeed, once you identify what you want to do, with overloaded methods you can easily add more methods with different signatures that all call your most basic function. The names on all the methods are all the same. Your code becomes very clear in it’s intent. It’s not saveEmployee(), saveUser(), it just becomes save(user), save(employee).  It’s important to note that I understand the former examples are very intent. However, the latter examples, when working in teams or groups, it’s much easier to learn and remember save(variable) and when you want to save an object and you don’t know if it’s an Employee or User you don’t have to worry about it because in most languages the compiler creates your switch or if statements for you.

 ( you should be able to see the next step with overloaded methods, which is to dynamically interpret objects you didn’t know about save(order), save(product) for example. Ruby on Rails made this kind of processing retro the past few years, but I’ve been doing something similar with coldfusion argumentCollection for years now. Check out Proxy if you’re interested in that. )

So to get to the demo, I created two functions with the same name eventHandler(), eventHandler(). My first method is my bucket. It’s where I want to throw everything into. My second method is my target method, the method that does the cool kick ass thing I want it to. It takes very specific arguments. Obviously it didn’t compile. So I created a namespace in the default package ( so I don’t have to import it ) called overload. I made my first method public and put my second method in the overload namespace. I reworked how I called the overload method and it compiled. To interpret my arguments I use a switch statement or if statements depending, like i was before. My code then becomes very intent. It at least accomplishes my goals with overloaded methods.

Overloadcode

 

A couple thoughts on this technique. First, I looked for but didn’t find that overload was a future reserved word in ActionScript. It feels like something that might be. Secondly, ActionScript should define overloaded methods, the compiler should implement them and and FB should support them.

Here’s the live demo. Right click for source.

 

 

 

 

 

 

 

April 16, 2008

My Struct() Custom Data Type that Binds

I’ve wanted to have a struct (hashtable) class that I can use for some time that also bind to controls like List, DataGrid, etc… Dictionary works fine, it just didn’t update the bindings. I just hadn’t figured out how to make sure how to make sure it’s dispatching events.  But I finally got around to creating a class that behaves more like a cold fusion struct that I can bind to. You can’t bind to it using brackets, but you can read values by key and set values by key. To bind by key there’s a method you have to go through.  You can get the class here

Struct.as (1 KB)

Here’s a brief run down of use cases:

Create a new Struct

[Bindable]

public var struct : Struct = new Struct();

Set a value 

struct[key] = value or struct.addByKey(key,value);

Read a value

struct[key] or struct.getByKey(key);

Bind to a value by key

{ struct.getByKey(key) }

Global classes and static global functions sans import

Global Classes

To define a global class simply create your class at the root of your project within the default package as follows:

package

{

public class MySweetNewType

{

}

}

 

 

No more importing. Although this is discouraged by flex builder there are some very legitimate reasons why you might want to have a global class defined that is automatically imported into everything. Utility classes, user classes, permission classes, custom data types are some that come to mind. My rule of thumb on this is that the frequency of use justifies the means. If I find I'm using a class over and over again and I have to constantly import it, I put it in the default package and refactor.

But if you’re using a class over and over again, it’s time to think about a reusable Library. Just drop your class at the root of your library and reference the project and it works without importing as well.

 

Global Function

You can’t define a global function that rests at the root of the package and automatically gets imported (that works, it shows up in code hinting tho). But you can define a class with a static function that gets you close enough. If you get creative with your class name ( remember class name and file name have to be the same ) you can get close enough to a global function as is necessary. An example is below. this allows you to call echo with the simple syntax of $.echo(‘hello’). This works good for functions you find very repetitive. Using the dollar sign as my class name makes it very apparent that it’s not just any old function. I’m not sure if this has any side effects so if anyone knows or finds out let me know. So far it’ has passed the smell test.

 

package

{

public class $

{

public static function echo(phrase:String):String

{

trace(phrase);

return phrase;

}

}

}

 

 

 

 

 

 

 

April 14, 2008

Me to Flex Builder Additional Compiler Arguments: "UR Dumped"

I’ve never been dumped via text message but I hear it’s en vogue these days. If it happened to KFed I guess it could happen to anyone. So don’t be so surprised when I say I gotta give the boot (If i knew who to text about this I would) to the Flex Builder Additional Compiler Arguments. I will no longer waste my time fiddling around with a growing list of compiler options that runs off my screen and

Compilerotpions

makes me wanna pull my hair out. I really only have about a quarter of my compiler options visible in the image above. So I’m moving on to a flex-config.xml file. It offers easier readability ( who doesn’t like easy). There’s an example that comes with the SDK and best of all I can now use the same config file in Flex Builder as I do in my automated Build Process. ( We use Microsoft build btw ). Isn’t that nifty. There’s some other great benefits to this as well. If you’re sharing projects and using custom meta data or other custom compiler options and you are not checking in your .actionScriptProperties and .flexProperties files (because you all don’t have the exact same system configuration), just Check the flex-config.xml file in with your code and then your developers now only have to remember one command line option as stated below:

Compilerotpions2

( so fresh and so clean )

Simplify your ANT builds as well. Instead of having alot of <args> you can just use one.  -load-config. You get the same build in ANT as you did in Flex Builder. Also, you’re not limited to an all or nothing load-config=flex-config.xml file. If you change the = to a += you get the options in Flex Builder Plus whatever you define in your config file. So you can have yer cake and eat it too. The syntax for customized config files follows the same pattern as the flex-config.xml file. So you can use it as a template to get started or use it as a reference as you go.

This was a dumping that was a long time in the making. I need more granular control of my projects.

 

 

 

 

 

 

 

Every little -as3 namespace bit helps ... I think

While trying to eke out every little last bit of performance in my flex app I ran across the -as3 compiler option. The LiveDocs state

Defines methods and properties of the core ActionScript classes that are fixed properties instead of prototype properties. When you set the "-as3" compiler option to true, the AS3 namespace is automatically opened for all the core classes. This means that an instance of a core class will use fixed properties and methods instead of the versions of those same properties and methods that are attached to the class's prototype object. The use of fixed properties usually provides better performance, but at the cost of backward compatibility with the ECMAScript edition 3 language specification (ECMA-262). 

I added it to my app, and ran some profiling. Not sure what to look for. If you have experience using it feel free to chime in now. Otherwise I guess I'll get back to trying to out-fox myself  doing nothing because there is no more hope.

 

— UPDATE : hat tip to josh for pointing this out. The -as3 compiler is automatically turned on. You’re supposed to use the -es compiler option if you do turn it off. Here’s a current link to the livedocs that gives more info.

 

 

 

 

 

April 04, 2008

A few things I wish Action Script supported

I’ve been learning alot of Erlang and Java lately. My last language romances were C# and ruby. I love learning new programming languages. It seems every single one of them has something to offer, if not a more simple and elegant way to program then a more obfuscated, bavarde and cluttered way not to program.

Through this I’ve been able to consistently develop in Flex and Action Script. On an almost daily basis for two years now and there are a few things I wish Action Script / Flex supported.

Method Overloading 

User Defined Functions ( that show up in the root, without a class name being in front )

Typed Variable Annotations

Although, there’s probably a lot more. I’d be the first to admit I’d abuse the User Defined Functions. Well, good news for me, it looks like there have been accepted proposals for two of my three wishes for ECMAScript 4.  ( I can live w/o UDF’s ) I’d be interested to get more involved with the ECMAScript 4 proposals if there was a user group and possibly a testing forum??? I haven’t found much on that front — might be too early. If you’re interested in the ECMAScript 4 proposals I suggest you subscribe to this blog by Francis Cheng. ( Hat tip to Ben for pointing me to it) I’ve never met Francis, but he comes out with stuff from time to time and funnels the proposals into something coherent that I can understand, and if I can understand it, then ya’ll can understand it.

 

March 06, 2008

Listening For All Events

Or Capturing All Events, Or Routing All Events.

This kind of reminds me of that phrase in Super Troopers where the guy is licking the window in the cop car and says “The snauzeberries taste like snauzeberries” which is to say, I literally and figuratively did the Homer “Doh” when this just dawned on me. I needed to listen for all events that come through a specific component. And I had tried a series of half steps and misdirections before I just simply overrode the dispatchEvent method in my component and it just simply worked.

 

override public function dispatchEvent(event:Event):Boolean

{

trace("I hate my life");

trace(event.type);

return super.dispatchEvent(event);

}

 

 

Tags:

February 11, 2008

Boo! I'm an Event Manager

For a contextual meaning of the following you’ll probably want to check out this post by Jesse Warden.

While in the course of building flex applications there almost always comes a time when events just don’t line up properly for whatever reason. For example Global Event Listeners that listen for events that reside in modules that may or may not ever get loaded. Renderers that are use in repeater/list/grid controls that may don’t define our events in their metadata. And also, events that are fired from NonVisual Components that may or may not reside in the Display List.

In all these cases, the difficulty resides in the fact that as a developer you may not have / know about the specific instance of the object you want to add your listener to. In most cases this is OK, because as long as the component is a visual component you can still capture that event by adding your listener above it and using capturing/bubbling. The backstop in this scenario is always the SystemManager where you can add listeners to. However, you have to make sure you bubble or useCapture.

In the case of Global Listeners using the SystemManager is fine. But if we’re nested in three or four screens and we want to have specific instance code run and no more, because we may have two or more instances of the same object on the screen at one time, we don’t want the event getting all the way to the SystemManager, ( and we need to remember to stop the event) A better solution would be to confine our event to specific context. A localized SystemManager of sorts. In the case of using a DataGrid custom renderer and dispatching the event we want to listen for the the event in the document that houses the DataGrid. The document object gives an instance level where we can dispatch and listen for events safely. The document object also makes sense from a coder’s point of view. If I create a Panel called MyPanel and stick a button in it that dispatches an event, and then create two or more instances of MyPanel, what we get is objects named like MyPanel0, MyPanel1, MyPanel2, etc.

To get to the basics of how and where we dispatch our events there are only a few things we need to worry about. First, there is always a point up the Application tree where our events can be captured. Thus, the listener is the only one that needs to know about where the rendezvous point is. The object doing the dispatching doesn’t need to care. The way I think about this is:

Listeners, need a rendezvous point from which they can capture the event. Dispatchers must know how to define their target.

To help me remember how to set these two events properly I created an EventManager class that hides the implementation of dispatching these events from me. I also created an AppEvent class from which I can extend my AppEvent classes. An AppEvent might be something like a UserEvent.LOGIN that is global, or might be specific to different sets of code in my app, like a ProjectEvent.PROJECT_ITEM_CHANGE event. All classes in my app can then import my EventManager class to make sure they can dispatch and subscribe to events in the context they need to.

The Signature on my Event Manager class looks like

public static function addEventListener( type:String, listener:Function, rendezvous:EventDispatcher = null, priority:int=0, useWeakReference:Boolean=true ) : void

public static function dispatchEvent(event : AppEvent, target:EventDispatcher = null ) : void

Some noticeable things about these two methods because at first look they look pretty harmless, in fact almost useless, and duplicated. First with my addEventListener, the noticeable thing is the rendezvous object that you can pass in and that defaults to Application.application. This allows you to look up and down the object chain to find the exact point where you want to add your listener. The addEventListener always uses useCapture, and the AppEvent class always bubbles so we don’t need to worry about whether the event will be caught or not. ( This is especially good for team scenarios where there’s always a fat fingered member that fancies himself a proctologist )

Second on the dispatchEvent method you’ll see that a target is allowed to get passed in ( it defaults to Application.application, which means Global) , which creates some interesting side effects and a lot of flexibility. Essentially passing in a target allows me to set the target of the event in scenarios where an event might not originate on the target. This is real handy when dispatching events that are defined off data as in ValueObjects, a good example might be when I want to dispatch that UserEvent.LOGIN event and I want my target to be a UserVO object. The actual login event might originate when the data arrives from the server with our user info. I can then propagate the UserVO throughout my system and anybody who cares can do something. Our UserVO might contain permissions and we might need to change our layout, or it might contain user preferences, etc.. 

The ability to set the target of an event is also a handy technique when using NonVisual components.  I pointed out in this article how to create a non visual component that is implemented in mxml. Jesse pointed out in his article that he’s changing his mind about using IMXMLObject, which is a fair argument, but when you think about events as Listener : Rendezvous, Event : Target and then realize you can switch out the rendezvous and target, it doesn’t take Tom Sawyer to paint the white fence white. Using our IMXMLObject and the dispatch event technique that I described above gives us the perfect vehicle to dispatch our events. IMXMLObject interface defines the following method

public function initialized(document:Object, id:String):void

We can then use the document object to dispatch our event into the proper context of where we want to dispatch it. Like I mentioned above, the document object comes in instances of objects we defined. From my previous MyPanel example, a non visual component that is implemented in mxml would get a document named something like MyPanel0 or MyPanel1. As long as we have an instance of MyPanel we can add our listeners to it.

In most cases, I just use the EventManager class to dispatch to the proper context. Rarely do I actually listen through it, but it’s there and can be handy.

I’d like to point out that this is by no means a substitute for the built in event lifecycle. It’s important to use this technique only when is necessary. And be very afraid of global events. Like most things global, Global Variables, Global Constants, Global Singletons, Global Warming, they can be very bad, if you don’t believe me, just ask him.

I’ve included a sample application demonstrating some of these techniques with links below. There’s also some more of my value object techniques I’ve been demonstrating, like setting a value object by passing in a form or xml and some other techniques that make app building simple, but I won’t get into detail on them unless someone asks or I run into one of these.

Here’s the demo:  I left traces everywhere so you can download the app and run it.

demo

source

 

 

February 05, 2008

My Boring Base Value Object

After some very encouraging remarks from Ark on this post I decided to make my Titles as boring as possible so all the left brain people in the world ( read about them here ) can understand me. If you want to tune out now now I’ll understand.

Or not, I’m really just interested in blogging about technology so I’ll keep to my thought and talk about using a Base Value Object . One of the things I never do is set individual properties on objects. I should be able to pass them an object, and they should know how to set themselves. I demonstrated this with that horribly named  post here, and I wanted to follow up that post with the technique I use to create value objects.

The concept is as follows: You have a lot of different value objects and no matter what you throw at them they know how to populate themselves, so that whether it’s an object returned from the server or it’s a selectedItem from a DataGrid the call to create a new value object should be the same. for example:

var user : UserVO = new UserVO(selectedItem);

var user : UserVO = new UserVO(event.result);

 

My UserVO looks like this. Notice it passes the args to the super function, and it’s only responsibility is to define what it looks like.

public class UserVO extends ValueObject

{

public function UserVO(args:Object=null)

{

super(args);

}

public var name:String;

public var email:String;

}

And finally my Value Object that does all the work.

public class ValueObject

{

public function ValueObject(args:Object=null):void

{

setVO(args);

}

public function setVO(args:Object=null):void

{

if(args == null)

return void;

for (var key:String in args)

{

// for some reason mx_internal_uid gets in the way.

if (key != "mx_internal_uid" && this.hasOwnProperty(key))

this[key] = args[key];

}

}

}

 

My base value setVO function is where everything takes place. You can make your objects dynamic and take out the check for hasOwnProperty(). Also, Examine the type of the args passed in to the setVO function to make it possible to pass in xml, or arrays, or any other sort of data type, I took out my checks for the purpose of brevity.

Well hopefully this post was drab enough to win over Ark. If you’re still in the mood, check out this.

brian..