Skip to content

Instantly share code, notes, and snippets.

@zEvg
Created July 8, 2011 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zEvg/1071783 to your computer and use it in GitHub Desktop.
Save zEvg/1071783 to your computer and use it in GitHub Desktop.
Utility for batching ArrayCollection's ADD event. For performance optimization
package com.zevg.utilities
{
import flash.utils.Dictionary;
import mx.collections.ListCollectionView;
import mx.core.EventPriority;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
public class CollectionEventBatcher
{
private static var collection2batchEvent:Dictionary = new Dictionary(true);
/**
* Batching add events. For performance purpose, problem is here https://bugs.adobe.com/jira/browse/SDK-30008
*
* IMPORTANT: Method batches only ADD events.
*/
public static function start(collection:ListCollectionView):void
{
collection.addEventListener(
CollectionEvent.COLLECTION_CHANGE,
batching_collectionChangeHandler,
false, EventPriority.CURSOR_MANAGEMENT, true
);
}
public static function stop(collection:ListCollectionView):void
{
collection.removeEventListener(
CollectionEvent.COLLECTION_CHANGE,
batching_collectionChangeHandler
);
if (collection2batchEvent[collection])
{
collection.dispatchEvent(collection2batchEvent[collection]);
delete collection2batchEvent[collection];
}
}
private static function batching_collectionChangeHandler(event:CollectionEvent):void
{
// handle only ADD events
if (event.kind != CollectionEventKind.ADD)
return;
var collection:ListCollectionView = event.target as ListCollectionView;
var batchAddEvent:CollectionEvent;
if (!collection2batchEvent[collection])
collection2batchEvent[collection] = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE, false, false, CollectionEventKind.ADD);
batchAddEvent = collection2batchEvent[collection];
batchAddEvent.items = batchAddEvent.items.concat(event.items);
// swallow this event
event.stopImmediatePropagation();
}
}
}
@zEvg
Copy link
Author

zEvg commented Jul 8, 2011

Here is use case:

var collection:ArrayCollection = new ArrayCollection;

CollectionEventBatcher.start(collection);
for each (var item:* in hugeCollectionInScope)
{
    collection.addItem(item);
}
CollectionEventBatcher.stop(collection);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment