Browsing articles in "Flex"
Feb 18, 2011

Mesh – A Persistence Framework For Flex

For awhile now, I’ve been wanting to create a framework at Mixbook for managing how data is sent back and forth from our Flex application to the server. We’ve had some downtime recently and I think we’ve come up with something pretty cool for the Flex community. It’s called Mesh, and it’s really simplified our persistence codebase.

In Mesh, you define the mapping of your models to backend services and the associations between your model classes. Mesh uses these definitions to determine how to query your backend for data. For instance, say we have a Customer who has many Order‘s. If you were to call customer.orders.load(), it will execute a find request on the orders service and populate the list with orders belonging to that customer.

Saving is also a lot cleaner. Each model and association has a method called save(). When called, it persists the model object to its defined backend service. Associations also track how your application modifies them. For instance, we can save two new Order‘s to Customer, then later in our code, remove one of the orders and update the order total for the other. When customer.orders.save() is called, Mesh will send a destroy request to the order service for the order that was removed, and an update request for the order thats total has changed.

var order1:Order = new Order();
order1.total = 9.99;
 
var order2:Order = new Order();
order2.total = 19.99;
 
customer.orders = [order1, order2];
customer.orders.save(); // persist order1 and order2 to the orders service
 
// update the total for order1, then remove order2 completely.
order1.total = 1.99;
customer.orders.remove(order2);
customer.orders.save(); // send a remove and update request to the backend service

We’ve also added some other great features, such as data validation and tracking which objects have changed, so only the objects that have been modified and are valid get sent to the server. Mesh is completely agnostic to the backend service you’re using. It can integrate with any REST, SOAP, or AMF service, and hypothetically, it should also be able to work with a SQLite database running in AIR.

Mesh is hosted at GitHub, and I’m progressively adding tutorials and guides on how to use the framework. Note that Mesh is currently in alpha, so there may be parts of the API that change in the coming weeks.

We’re releasing this framework as open source under the MIT license, which means that it’s completely free to use in commercial projects. We welcome feedback on ways to improve the API, or new features that you think would be beneficial to a framework such as this.

Feb 3, 2010

Making ActionScript Look Beautiful: Increasing Readability and Loosing Verboseness

After playing around with languages such as Ruby and Groovy, I’ve been yearning to loose a lot of the verboseness of ActionScript. I feel that many languages tend to be overly expressive, and hide the concepts of what your code is actually doing.

Lets take a simple example of a snippet of code that represents, Is tomorrow after today?

function isTomorrowAfterToday():Boolean
{
    var now:Date = new Date();
    var today:Date = new Date(now.setHours(0, 0, 0, 0));
    var tomorrow:Date = new Date(now.setDate(now.date + 1));
    return tomorrow.getTime() > today.getTime();
}

Continue reading »

Dec 8, 2009

Help Dan find a Flex Engineer and get a free paid trip for 2 to Hawaii

Put me in touch with a Flex Engineer that we hire, and we’ll fly you and a friend to Hawaii, put you both up in a hotel, AND fly you back. Huh? Sick of making your friends jealous from all those Hawaii excursions?? Well, you have the option to choose the tech package, which includes a 42″ LCD TV and Macbook Air. Gez, not interested in that either?? Then eBay it, and get cash for tech!

Take a look at our job posting, which has all the details about the position.

A little info about the company. Mixbook (www.mixbook.com) is a profitable, rapidly-growing San Jose, CA, startup that allows people to collaboratively create photo books through a powerful online Flex application. Users can share their creations online for free online – like a YouTube for photo books – or purchase bookstore-quality copies of their work to share in real life (see http://www.mixbook.com/printed-photo-books). Over 2 million people have created over 5 million photo books on Mixbook’s platform – your work will impact a community of millions.

We offer competitive salary and generous equity stakes, along with benefits, a new Mac or PC, dual monitors, and a chance to impact a community of millions. We’re looking for talented and passionate people who take pride in giving customers a phenomenal and enriching online experience.

Please share!

Mar 10, 2008

Saving Flex’s Application State to a Database

Bill Sanders has a great post on the Memento design pattern over at his blog. After reading it, I thought I’d chime in and post a technique that takes the memento one step further. This approach allows you to serialize a Memento object into a ByteArray and save it into a database. Then, retrieving the Memento object from the server, dynamically instantiated it, and restoring its previous state.

One major draw back to the Memento, as you’ll see, is that restoring an object’s state can be a very expensive operation. Especially in a Flex environment where restoring a Memento could trigger a large display list invalidation. For that reason, the Memento is not always the ideal pattern for implementing undo/redo functionality. The alternative pattern for implementing this functionality is the Command pattern. With the Command pattern, each command is only concerned about a particular action to get to the current state of the application. With this, you can have an undo() method in each of your commands that undoes whatever action was performed in your execute() method. Continue reading »

Oct 6, 2007

CollectionEventKind.RESET, WTF Does That Mean?

When handling Flex’s collection change events, most of the change types are pretty self-explanatory. For example, CollectionEventKind.ADD is when an item is added to the collection, or CollectionEventKind.UPDATE is when an item’s property inside the collection changes. However, there’s this ambiguous change type called RESET. The documentation does a wonderful job of describing when this type of collection event is fired: Indicates that the collection has changed so drastically that a reset is required. (ASDoc Link)

Digging through ListCollectionView provides some better insight of when RESET is dispatched. Anytime a collection is passed to ListCollectionView.list, and both the old list and the new list has items in it, it will fire a reset collection change event. Here’s the code Adobe uses for setting a list on ListCollectionView:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public function set list(value:IList):void
    {
        if (_list != value)
        {
            var oldHasItems:Boolean;
            var newHasItems:Boolean;
            if (_list)
            {
                _list.removeEventListener(CollectionEvent.COLLECTION_CHANGE,
                                          listChangeHandler);
                oldHasItems = _list.length > 0;
            }
 
            _list = value;
 
            if (_list)
            {
                // weak listeners to collections and dataproviders
                _list.addEventListener(CollectionEvent.COLLECTION_CHANGE,
                                       listChangeHandler, false, 0, true);
                newHasItems = _list.length > 0;
            }
 
            if (oldHasItems || newHasItems)
                reset();
            dispatchEvent(new Event("listChanged"));
        }
    }

Lastly, ListCollectionView is a pretty useful class. A lot of new Flex developers go straight to using ArrayCollection, and forget about its father, ListCollectionView. This collection allows you to apply different sorts and filters on a collection without directly modifying the wrapped collection. You can also call addItem() and removeItemAt() on ListCollectionView and have it modify the wrapped collection. Pretty nifty! Here’s an example of it in action:

1
2
3
4
5
6
7
8
9
10
11
var col:ArrayCollection = new ArrayCollection();
col.addItem('a');
col.addItem('b');
col.addItem('c');
 
var wrapper:ListCollectionView = new ListCollectionView(col);
wrapper.removeItemAt(0);
wrapper.removeItemAt(0);
wrapper.removeItemAt(0);
 
trace(col.length); // traces: 0
Sep 24, 2007

When to Use Weak References

Understanding when to use a weak references, versus strong references can be a confusing one. It took me awhile to fully grasp when, and when not to use one over the other. On top of that, there’s very little documentation on the LiveDocs about the subject. Under the documentation for IEventDispatcher.addEventListener(), it states:

useWeakReference:Boolean (default = false) — Determines whether the reference to the listener is strong or weak. A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not.

And here’s what they have listed for the Dictionary’s constructor:

weakKeys:Boolean (default = false) — Instructs the Dictionary object to use “weak” references on object keys. If the only reference to an object is in the specified Dictionary object, the key is eligible for garbage collection and is removed from the table when the object is collected.

Ok … thanks. So, I did some Googling, and both Ted Patrick and David Coletta have much better information on the subject.

The basic idea behind strong references and addEventListener is this: when you call addEventListener and you pass it the function that you want to be called when the event fires, the event dispatcher is actually grabbing and holding a reference to that class and function it contains. As we all know, an object won’t be garbage collected until every reference to it doesn’t exist anymore. This insures that the event dispatcher always has a reference to the function that needs to be called. However, if you’re not careful, this can be a breeding ground for nasty memory leaks.

So, here’s my short list of do’s and don’ts related to strong vs weak references and event listeners:

  • Always use a weak reference when adding an event listener to a class that’s a singleton, or any object that you expect to live throughout the life of your application. Remember, this applies to most of Flex’s manager classes, including the SystemManager, and any event dispatching classes that your singleton’s contain.
  • Always use weak references when adding Cairngorm commands. The event dispatcher in Cairngorm is a singleton, and will always keep references to those command classes.
  • According to Ted, weak references are 10x slower. (True when referring to member access, but not event listening.)
  • It’s safe to use strong references when you’re adding an event listener to itself (i.e. the instance dispatching the event).
  • You should use a weak reference when adding an event listener to the Timer class.
  • Lastly, always make sure to clean up and remove any event listeners your classes are using when they’re no longer needed. I follow .NET’s approach, and I have an interface called IDisposable. This interface contains a single method called dispose(), and inside I remove any event listeners that the class might be using. Additionally, you could clean-up any BitmapData objects you might be using, among other things. Most, if not all, of my classes that I write implement this interface, and I just make sure to call dispose() when I know the object is no longer needed.

If there’s anything else to look out for, I’d love to hear them. It’s always good to be proactive when it comes to memory leaks.

Aug 31, 2007

The State Pattern in Flex 2

Photoshop Tools ThumbI’m currently working on Flex project at Quality Attributes Software that requires the use of a set of tools, similar to Photoshop, to manipulate a drawing canvas. Some examples of tools might be a drag tool, a selection tool, and a zoom tool. I thought to myself, “Ok, simple enough. Throw all the logic into a switch statement inside a generic on click button handler.” So, when a user clicks on a new tool, disable all the functionality from the previous tool, and enable the functionality of the new one. Ugh! This was a complete disaster. What happens when you expose all this logic, is that you run into some very highly coupled code. Meaning that each tool is essentially keeping the state of the other tools. Yuck!

There’s definitely a better way to handle these situations, and that’s by using the state pattern. Essentially, I turned each tool into a state. So when a user clicks on the Selection Tool, the program changes its state to use the functionality of selecting objects on the drawing canvas. I hide all this logic behind an interface, and each tool is represented as a class that implements this interface. If you’d like some code examples of this pattern, William Sanders has a great write up over at Adobe’s Developer Center.

Jun 24, 2007

No Dice with Yahoo Maps and AIR

Spending the last couple weeks refactoring Cayri’s code to be more modular, I was excited to start working on the AIR version of Cayri this morning. So I started up Flex Builder, drug my custom Yahoo Maps control onto the canvas, compiled the project, and got this sweet error:

Error: Error #2067: The ExternalInterface is not available in this container. ExternalInterface requires Internet Explorer ActiveX, Firefox, Mozilla 1.7.5 and greater, or other browsers that support NPRuntime.

This is just a heads up to those who are using an ExternalInterface work around for AS2 to AS3 communication, and are planning on moving your projects to AIR.

Ugh.

About Dan

  • I'm the Lead Software Architect at Mixbook. A rapidly growing online photobooking and scrapbooking company.
  • I built Cayri, an online monitor for flight simulator networks.
  • I enjoy learning guitar, astronomy, beer, music, programming, and driving with no apparent destination.
  • I live in San Jose, CA.

Categories

Twitter