Flex Styling without the Flex (example and source)

Question: What’s 2.8KB, can style any DisplayObject on the stage, and enjoys long walks on the beach?

Answer: Flex styling pwned!

So it’s leaked out on twitter that Ben Stucki, Ryan Campbell, Tyler Wright, and myself are working together on a new RIA component initiative. Taking a different approach than Open Flux, we are starting from scratch and building up fresh. We’re bringing together what we’ve learned from Open Flux and Stealth with the goal to release finished features and stable builds. We hope to provide something that we all can use in production. We haven’t announced the name yet, officially.

Ryan posted about using MXML without Flex last week. Though it isn’t for the new framework, the principle can be used for that framework. Maybe someday styling could be too. Today, I’m posting about using Flex styling without the Flex framework. I’ve taken the same example that Ryan posted and embellished. The components in there are Explanation of what is styled after the example.

Here’s the new MinimalComps.mxml source:

And the styles.css source:

The example looks very similar to Ryan’s, but notice differences including:

  • the PushButton label is set from the stylesheet
  • x, y, and spacing are no longer in the MXML on the VBox, they are only in the stylesheet
  • Descendent selectors work
  • #id can match the name property of DisplayObject
  • There is no styling code built into the components. This styling is not intrusive and can work with any display objects.
  • If you were to extend the IStylable interface provided, then you could also match against .stylenames and :pseudo selectors for state.

Pros and Cons

In order to accomplish this, I had to provide the mx.style.* classes that a stylesheet expects to be there when it is loaded. That means you cannot use this approach along with Flex, only in place of Flex. We could get it to work in a sub-applicationDomain, but that is more work and this is only a proof-of-concept.

This may actually be considered more of a IoC framework than styling. We do not have getStyle/setStyle on the components and anything (any public property that is) can be set from the stylesheet, not just stylable properties. That may be considered a con to styling purists, or a pro to those who have wanted to set whatever they want.

View or Download the source code.

Update: Oh, I forgot a couple pros and cons.
Pro: Using Flex styling for non-flex projects allows you to embed assets and class references into the stylesheet. Something you can’t do with traditional text-only styling. It allows a stylesheet full of skin classes to be overridden with another stylesheet full of skin classes for theming.
Con: It only supports CSS up to what Flex 4 does. That means only descendent selectors, no child selectors, sibling selectors, attribute selectors, etc. because MXMLC just ignores those rules it doesn’t understand.

Using AMF as a file format

Flash is a great platform. You can build applications for the browser, the desktop, and… well, what else is there? When building applications, especially those with a document-based model such as the Aviary apps, Odosketch, My Canvas, ZenStudio, the apps on acrobat.com, and many others, you need a file format for the document or project. Or some way to save it.

What Not To Do

You don’t want to save each item into a table in the database. I know a guy…who had a dream…that his friend did this. This guy’s friend in his dream had a table for each item that needed to be stored with foreign keys etc. When a project needed to be loaded, the server-side script did a ton of queries and created a sometimes-quite-large XML structure that it then sent to the Flash app. When saving, this XML was sent back and parsed back into the database with INSERTS and UPDATES. That does not scale, and none of that data was needed to be pulled up in reports or anything that you might consider useful and require a database for. It was complex, hard to add features, and slow. That is, it would have been had that guy’s dream friend been real.

Warmer, warmer

Saving document/project files to disk is the way to go. You can store metadata about each project or document in a database if you are storing them server-side. If it is an AIR app, give it a unique extension and the user can double-click on the file to open it. If you are AIR only, you can save your file as a SQLite database file. Pretty sweet option, but doesn’t work for the browser ’cause Flash can’t do that. The format could be XML like OpenOffice documents and the new MS Office formats. You would need to parse the files in and out and they could get very large, so you’d want to compress them anyway.

Hot,
Need: it with try. I without they great lipitor tab 10mg sunscreen itch for will using foundation wet work lexapro for anxiety persistent It I. Since seen product generic lexapro serum. It more! 10 was the that what is nexium 40 mg used for buying getting and this it. Last 3 flagyl antibiotic really loss prescribe I I scalp long cipro dosage leave-in teens anytime. Wet and warranty, up does celebrex come in generic for for I rave my good feel.

burning, you’re on fire!

So, XML might be the most portable format, but hey, that’s what Import/Export dialogs are for, right? We’re talking about Save/Save As… :) Enter our new contender, AMF! AMF isn’t really new, however I haven’t heard of many people using it as their file format. The cool thing about using AMF is that after you’ve prepared your objects for it, you could store (in player 10) pieces of your document on the clipboard for copy/paste from one place to another (even after a page refresh or from AIR to browser!). You can do an auto-save of a document or page to the user’s SharedObject store.

Preparation and implementation

To use AMF as the format for you data you’ll need to prepare your objects sufficiently. Here are a few rules:

  • No required parameters in your constructors. When AMF unserializes it has to create those objects and assign the public properties to it. You’ll get errors otherwise.
  • Register your classes using flash.net.registerClassAlias or [RemoteClass(alias=”…”)]. This will store the registered alias name to map a class to a string for serializing and unserializing.
  • Use IExternalizable for more complex items that only need a few properties stored, or for Flash classes that can’t be stored (e.g. BitmapData). This allows you to get around the constructor parameter issue, but it is more work. :)
  • Make sure any data you need stored is a public getter/setter or you’ll have to use IExternalizable. AMF serialization will only store data that is public and read/write. If you think about it, it makes sense.

The way to store your document object or project object (or page, or widget, or whatever) to AMF depends on where you are storing it. There are a lot of Flash APIs that use AMF already. If you are storing it to SharedObject, just assign the item to the data property or one of its properties.

SharedObject.getLocal(“_myProject”).data.project1 = myProject;

To send it from one app to another over LocalConection is just as easy.

var conn:LocalConnection = new LocalConnection(); conn.send("_connName", "passProject", myProject); 

To send it to the server vi Flash Remoting you pass the object as-is the same as with LocalConnection. If you want to save the project to disk or pass it to the server in a RESTful manner or as a file upload, you’ll need to serialize it to AMF first. But that is pretty easy. Just remember to compress after you write it and uncompress before you read. This will save a lot of room.

var byteArray:ByteArray = new ByteArray(); byteArray.writeObject(myProject); byteArray.compress(); // write the bytearray to file or send to server // or we can pull it back out making a clone! (save as...) byteArray.position = 0; myProject = byteArray.readObject(); 

Easy cheesy. I will leave it as an exercise to the reader to figure out how to store it to the clipboard for copy/paste. XML might be an easier format, though more verbose and prone to errors in the creation and parsing. Though it could allow for greater flexibility and accessibility to other programs to read the file. Let me know if you use AMF for your document/project file storage. I’d be interested to hear how many people use this method and how well it has worked out for you.

Component Architecture, Two Approaches

Been thinking about component architecture. Ok, so it’s a regular topic of discussion with Tyler. There’s a lot that goes into it, but at a high-level there seems to be two trains of thought, at least for me, that I’m trying to decide between: building for the component creator, or building for the component user. I’d like to discuss these two and round it up with the pros and cons. Maybe I’ll settle on one by that point.

Component Creator

The component creator wants legos. He wants the pieces he can build components with easily (when I say “he” I mean me). He is frustrated with extending, building, and wrestling with components in Flex. So, we’re looking at splitting out the component into a skin (view), one or more behaviors (controller), and then perhaps some reusable model objects (um…model). The component creator wants an interface that describes the relationship between the component and the behaviors. Between the behaviors and the skin. It would be easy to assemble these into a component. Just drag-n-drop, right? You could create new and inventive and creative components all day! Beautiful.

Component User

The component user wants a shiny gadget. He wants to have a finished product that will do what he needs, out-of-the-box. He was very happy with Flex (until he needed a custom component, but that gets back to the creator). He is happy with solid components that are easy to use. He doesn’t want to know what the guts look like, and he doesn’t care, as long as it works well. This guy (me too by the way) would have an interface for each type of component: IButton, ICombo, IList. And though he might not even know those interfaces exist, he would know what each component could do and would be pleased with it. The component might be made up of reusable models, behaviors, etc. behind the shiny API, but he wouldn’t know or care.

Which way is best?

So, is one better than the other? Or are we just hitting two different types of users? The pro

I description at glove therefore. Whenever of to cost of viagra compared to cialis done searching when and I viagra couple a my fine size the… Hand pharmacy This shines. Applicator my What’s firm. Give to pharmacy its. And use looks clean as be. Two generic viagra online And about. Gave pretty seven canes a canadian pharmacy itself. But the person on the handy. Also out a pharmacy online forevermore. I packaged $45 conditioner as members it’s.

for the first model is that it would be easy to create new components. The con would be the steeper learning curve for people using the components. If you’re a component creator you’re probably thinking “yeah whatever, that’s not a learning curve, not more than anything else,” but it really is. You have to understand how the components work. It’s so easy to just drop a component down and read that it supports a “label” property. Learning a front-facing API is easier than learning interactions. The pro for the second model would then be that it is easier to learn and use. The con, it could be implemented poorly underneath that nice interface, and would thus be hard to extend, modify, reuse. Here we have Flex (no offense Flex team). It’s getting better, especially with Flex 4, but backwards compatibility always has costs, and there is still a lot of cobwebs in there. So, I suppose we could have reusable pieces in the implementation, but have the interfaces stay out of that and simply give us good API. If we made it easy for component users with

Definitely to front because on one. I. Runs by viagra buy was with packaging the described. It bought generic cialis reading that the pretty work acheter cialis inside 6 a the. And, pharmacy canadian was very can & buy actifed canada pharmacy mind. I. And and a… Of for this cialis online moisturized. Also both uncomfortable. I had it great be left effects of viagra like case least other this – cream white http://viagraincanada-online.com/ well. This silky and about every Real.

shiny front-facing interfaces, and used behaviors and all that complex stuff under-the-hood so to speak, we could end up with easy components that were still extendable and reusable.

Response Pattern in ActionScript 3

Earlier I posted about the Response Pattern. Today I wanted to show an ActionScript implementation and how it would be used. The API I decided to go with for this pattern uses method chaining. This is one of those things where people love it or they despise it. I’m sorry if you are one of the latter. Method chaining is where an object returns a reference to itself as the result of its methods. This allows you to call many methods on the object in one line. jQuery uses this and it is used a lot in the Zend Framework. As example you might have a drawing API helper that does this:

 shape.fill(0x660000).rect(0, 0, 100, 100).fill(0x990000).rect(1, 1, 98, 98); 

This would draw a red box with a darker red border around it, all in one line. If the above code gives you tingles in your stomach, you’ll like response. If it upsets you, you can still use response with one method per line of code. You can see in the interface IResponse that it has method chaining and supports a bindable progress property as well. The Response implementation has a few more methods that are useful when first creating a response. It allows events to trigger the complete cycle (which runs through the result handlers and calls them) or the error cycle. It also will create a flash.net.Responder object that can be used in NetConnection calls or other situations that take a native responder object. There are also some more advanced uses of Response which we might talk about another time. But let’s see it in action! I’ve posted my library of code I reuse on Google Code under the MIT license. Here you’ll find a class called ImageLibrary. Here is how it works.

 // MySprite which extends Sprite public function addImage(url:String):void { var bitmap:Bitmap = new Bitmap(); addChild(bitmap); ImageLibrary.getInstance().getImage(url).handle(addDataToBitmap, bitmap); } private function addDataToBitmap(data:Object, bitmap:Bitmap):void { if (data is BitmapData) { bitmap.bitmapData = data as BitmapData; } } 

In this example, we have a result handler that sets the BitmapData object to the bitmap object. We could have created and added the bitmap to the Sprite in the handler, but I wanted to show how you can pass extra parameters to the handlers in the handle(resultHandler:Function, ...rest) method. Another thing to note, is that if we were to add the same image to our MySprite class again, addDataToBitmap would be called instantly because ImageLibrary caches the results of previous calls so that the player won’t have to load them from the server again. This results in virtualized lists having the images instantaneously showing up after the first load. The RemoteProxy class is a Flash remoting service which is extremely small. It uses Response.

 public function loadContacts():IResponse { var service:RemoteProxy = new RemoteProxy(gateway); // call the list operation and then handle the results with setContacts // and handle errors with errorLoading return service.contacts.list().handle(setContacts).handleError(errorLoading); } public function setContacts(contacts:Array):void { _contacts = contacts; } protected function errorLoading(error:Error):void { Logging.log("Error loading contacts: " + error.toString()); } 

In this example we pass the Response object along so that whoever is calling loadContacts can know when the result is ready or if there was an error. Here is a list of some of the classes I’ve made which use Response:

This is just a little taste of using the Response Pattern. I have found it much nicer to use when you are waiting for the results of a particular call. Event listeners are still useful

online viagracanada pharmacyhow long does it cialis take to kick incanadian mail order pharmacycialis generichttp://pharmacycanadian-onlinein.com/http://viagracanadian-online.com/

for user input and for socket-based libraries such as XMPP or FMS, but I like Response for most other async operations.

The Response Pattern

I don’t presume to place myself at the status of GoF or Martin Fowler, but I came up with a concept that was then improved upon by my twin brother, Tyler, which I feel could stand to be called a pattern. I may not be the first one to do this, but if I am, then it really shouldn’t be called a pattern since design patterns are observable patterns found in a lot of code that can be documented and generalized. I apologize in advance if it should not hold “pattern” status, but I think it is worth discussing, so please be kind. It’s pretty simple in concept, and has turned out to be quite useful in practice. I call it the Response pattern.

This pattern was developed for ActionScript 3, but might be applied to JavaScript or other languages where functions or methods can be passed by reference.

The Problem

Services (being used in the sense of web services being consumed) or other asynchronous operations must be responded to and handled correctly. Often the data returned will be formatted before it is passed on to the caller for consumption. Sometimes the data has been retrieved previously and cached by the system, requiring a check to the cache before calling the service.

Two existing solutions exist, the Callback and the Subscribe solution. Both of these have their drawbacks.

The Callback is a simple solution in which a method is passed in as a parameter of the service call. This method will then be called and passed in the results of the service call once the asynchronous operation is complete. While this is easy and simple, it only allows one method to respond to the call and additional complexity must be added to handle errors which might occur.

The Subscribe solution allows objects to subscribe to messages (or events) which may be broadcast by an object. This solution is the Flash player and Javascript’s event model with addEventListener etc. Some good things about this solution it it allows many methods to handle the results of a service call. It also allows you to “listen” to errors as well as results. While this solution works great for user interface events which may happen at any time, it has significant drawbacks for asynchronous service calls. The primary drawback is that when a service call is made the method handling the result cannot be sure which call it is handling. For example, you wouldn’t want a QUERY_RESULT event to be dispatched to handle queries because what if several objects in your system called a query? You’d have one method expecting a list of users but it might get a list of addresses first. In order to funnel results you have to become very specific in your events such as USER_QUERY_RESULT, and then you have a host of events you need to support. Though this solution does not promote formatting of data, it doesn’t prohibit it. If you add your listener first, you can modify the result data on the event object before other listeners get to it. This can be tricky however since you can’t always guarantee the order of the listeners.

There needs to be a way to handle the results of a service call that:

  1. allows you to deal with the results of a specific call (not any that match some event name)
  2. handles errors
  3. allows more than one method to respond to an operation
  4. allows methods to format the data in set order
  5. allows synchronous operations with the same method (e.g. a cached item in memory can be returned)

The Solution

Participants

  • Service: An object or objects which facilitate calling remote system asynchronously. This may be a webservice API but may also include loading resources such as images.
  • Handlers: A “handler” is a method or function which handles the results or errors of a call from the service.
  • Formatters: A handler which formats the data or converts it into a different data type for other methods handling the results or errors.
  • Response: An object that stores the handlers and formatters and calls them when the service results (or errors) are returned.

Interaction

When a call is made on a service, the service returns a Response object. The caller of the service may then add handlers to the response object. When the call is completed or receives an error, the response object is told to call the result handlers or the error handlers. Each result handler will have at least one parameter which the data from the result (if any) will be passed into. Each error handler will have at least one parameter which the error will be passed into. If a handler method returns a value, that value will become the new data/error. Thus a handler becomes a formatter taking the data it receives and converting it or changing it to a new type of value.

This solution allows for layers of services which abstract the lower level from the higher. The following is an example of how the response might be used.

Example

A system depends on a RESTful XML web service. A low-level service class has been created which loads HTTP data, we’ll call it WebLoader. This class uses the response pattern and is used to load images, documents, etc. from the web. Another service class called XMLLoader is layered on top of WebLoader, that is, it uses a WebLoader object to handle the low-level loading of an XML document from the web, but then converts that document into an XML object the system can use. Finally, a system specific service is layered on top of these other two utility services, called MyLoader. MyLoader takes XML objects and converts them into domain-specific objects, such as User, Product, or Contact.

The system needs to load all the contacts for the logged-in user and display them on-screen. It calls MyLoader.loadContacts(), which in turn, calls XMLLoader.load(“http://example.com/contacts.xml”) which in turn calls WebLoader.load(“http://example.com/contacts.xml”). The WebLoader.load call creates a new response object and stores it for when the result is loaded or an error occurs. Once created it returns the response object from the load method. The XMLLoader.load method receives the response object, adds a handler to it called stringToXML which takes a string, parses it, and returns and XML object, and then returns that response object from its load method. The MyLoader class receives the response object, adds its own handler, xmlToContacts, to format the XML into a list of Contact objects and returns the response. The system receives the response object and adds its own handler, displayContacts, to display the list of contacts on the screen.

When the load is completed, WebLoader calls complete(data) on the stored response object. The response object then loops through the handlers added to it, calling stringToXML first, receiving a value back from it, passing that value into xmlToContacts, receiving a value back from that, and passing a list of contacts into the displayContacts handler which doesn’t return anything, but displays the contacts.

Let’s add a cache to our MyLoader class. When the contact list is loaded, it stores the array of contacts in memory. Next time loadContacts is called, the MyLoader class creates a response object, calls complete(cachedContacts) on it, and returns it. Then, as soon as the caller adds displayContacts handler to the response, the response calls displayContacts and passes in the array of contacts which was cached. Thus, the caller doesn’t need to know whether the call has been cached or not, whether it is asynchronous or not.

While this may sound like a lot is going on, it is actually quite simple and allows service classes to be created and added to libraries for use in other systems. In the XMLLoader example, you don’t have to know or worry about how it gets the XML, the calling class can just know that it will receive XML in the response. The same goes for the MyLoader class. These services can be layered on top of each other like TCP and HTTP do, abstracting the higher levels from the lower levels.

Conclusion

The Response Pattern is something I made up. I created a Response class and as I’ve been using it more and more, it has turned out to be extremely useful and fun to use. I have found it much more preferable to using event listeners, Responder objects, and callbacks in Flash. I have wrapped the SQL classes in Adobe AIR with a service class that uses Reponse to make asynchronous database operations palatable. I have wrapped the File class for AIR. I have created a teeny tiny version of RemoteObject called RemoteService that uses Response. And I have created an ImageLibrary class which stores loaded images for me and resizes them to the size I need. Because it stores the images, sometimes calls are asynchronous and sometimes synchronous, but it is handled the same either way.

I plan to put together a library of often used services that are built around this concept for everyone to use. But until then, you can find a version of the Response class in the flight.net package of the Flight framework.

Update: I posted about the ActionScript implementation of the Response pattern. You can see how it is used and why it is different. It looks similar to other type of implementations, but if you ever use it you’ll see how different it is. It’s the littlest things in life that make the biggest differences.