Collection (class)

Categories:Elements

Overview

Summary

The Collection class and its subclasses are Array-like classes designed to collate and modify groups of related elements, mainly within the Flash visual environment such as Elements and items.

Contents

Concept

The (completed) classes in this group include:

Each collection stores an Array of elements of a particular kind (e.g. stage instances, or library items), and allows you to modify them en-masse (for example renaming, arranging, or changing the color of) with built-in methods specific to each Collection type.

The core Collection class, which this article discusses, provides a set of base methods for iterating over and modifying the Array of elements each of the subclasses contains, and are used mainly by the methods declared in these subclasses.

More information on Collections and their background can be found in the Introduction to Collections page.

Usage

Basics

Collections are typically instantiated using the new keyword, and are then modified using built-in methods on each collection type, as in the following hypothetical example:

var collection = new Collection(items);
collection.doSomething();

A concrete example of the above would be using an ElementCollection to sequentially rename selected stage elements:

var collection = new ElementCollection($selection);
collection.rename('clip');
Chaining

Note that all collection methods return the current (or a modified) collection, so it's possible to chain commands as in the following example:

var collection = new Collection(dom.library.selectedItems);
collection
    .rename('Bitmap')
    .attr('allowSmoothing', true);

See the support pages for both the Item Selector and Element Selector for more information.

API

The base Collection class provides core functionality for all Collection classes. As such, most of the examples on this page will simply use an array of Strings to demonstrate the functionality.

Collection

Base Collection class with core methods to iterate over and manipulate elements

Parameters:

  • elements Array An array of elements

Returns:

  •   Collection The original Collection object

The following example creates a collection:

var collection = new Collection('one', 'two', 'three');
trace(collection);
[object Collection length=3]

Properties

elements

The internal elements of the collection

  • Type: Array
  • Access: Read

The elements property of a collection is its internal array of elements or items that are modified by the collection's methods.

Usually, you won't access this directly, but it will be modified by collection methods, or your own callbacks, via each() or other methods. The following example traces the elements array's length to the Output panel:

var collection = $('*');
trace(collection.elements.length);
5

Standard Methods

The standard methods are used to iterate over and find elements in the collection.

each(callback, arguments)

Calls a function on each element in the collection in forward order

Parameters:

  • callback Function A callback function to fire on each iteraction
  • params Array An optional array of parameters to pass to the callback function
  • scope Object An optional scope object, defaults to the collection

Returns:

  •   Collection The original Collection object

The following example modifies items in the collection in the order they were added:

var collection = new Collection(['one', 'two', 'three']);
collection.reach( function(element, index, elements){ trace(element); } );
one
two
three

reach(callback, arguments)

Calls a function on each element in the collection in reverse order

Parameters:

  • callback Function A callback function to fire on each iteraction
  • params Array An optional array of parameters to pass to the callback function
  • scope Object An optional scope object, defaults to the collection

Returns:

  •   Collection The original Collection object

Processing elements in reverse order is usually necessary when deleting elements from the collection.

For the sake of brevity, the following example traces the items in the collection in reverse order:

var collection = new Collection(['one', 'two', 'three']);
collection.reach( function(element, index, elements){ trace(element); } );
three
two
one

indexOf(element, fromIndex)

Returns the first index at which a given element can be found in the array, or -1 if it is not present

Parameters:

  • element Object Element to locate in the array
  • fromIndex Number Optional index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from front to back. If the calculated index is less than 0, the whole array will be searched.

Returns:

  •   Number The first index at which the element is found, or -1 if it is not present

The following example displays the 0-based index of the item "two":

var collection = new Collection(['one', 'two', 'three']);
trace(collection.indexOf('two'));
1

get(index)

Gets an element from the collection

Parameters:

  • index Number Gets the nth object in the collection

Returns:

  •   Object An object

The following example returns the second item in the collection:

var collection = new Collection(['one', 'two', 'three']);
trace(collection.get(1));
two

find(value, property)

Finds and returns elements (by name, or other property) within the collection

Parameters:

  • value String A String (wildcards allowed) name or property value
  • value RegExp A RegExp name or property value
  • value Value Any value
  • property String The name of a property to match against. Defaults to "name"

Returns:

  •   Array An array of matching elements

The following example finds and returns the reference to the element named "star3":

var collection = new Collection($selection);
var star = collection.find('star3').pop();
trace(star);
[object SymbolInstance]

The following example uses a wildcard to identify all elements whose names start with the word "star", then selects them on stage:

var collection = new Collection($selection);
$selection = collection.find('star*');

The following example uses a Regular Expression to find and return all elements whose names end with 1, 2, or 3. Note that the ElementCollection is returned using the ElementSelector function:

var elements = $('*').find(/[123]$/);

Note that by default, the property matched in all find operations is name, but the second argument allows you to use an alternative property.

In this example, an array of graphic objects is passed in, then the ones which are set to play once are returned from the find() operation:

var collection = new Collection(graphics);
var elements = collection.find('play once', 'loop');
list(elements);
[object ElementCollection length=3]: Array (depth:1, objects:0, values:3, time:0.0 seconds)
-------------------------------------------------------------------------------------------
array => Array
	 0: "item: 2 - elements/shapes/square"
	 1: "item: 2 - elements/shapes/triangle"
	 2: "item: 2 - elements/shapes/square" 

Whilst this is a good way to grab items from an existing collection, creating a new collection from scratch could be more-easily accomplished using the ElementSelector and an attribute expression:

var collection = $('[loop=play once]');	

Manipulation Methods

The manipulation methods allow you to alter the content of the collection programatically.

add(elements)

Adds elements to the collection

Parameters:

  • elements Array Adds elements to the collection

Returns:

  •   Collection The original Collection object

The following example adds some new items to the collection:

var collection = new Collection(['one', 'two', 'three']);
collection
    .add([4,5,6])
    .list();
[object Collection length=6]: Array (depth:1, objects:0, values:6, time:0.0 seconds)
------------------------------------------------------------------------------------
array => Array
	 0: "one"
	 1: "two"
	 2: "three"
	 3: 4
	 4: 5
	 5: 6

remove(elementsOrValue, property)

Removes elements from the collection

Parameters:

  • elementsOrValue Array An Array of elements
  • elementsOrValue String A String (wildcards allowed) name or property value to find elements by
  • elementsOrValue RegExp A RegExp name or property value to find elements by
  • value Value Any value
  • property String The name of a property to match against. Defaults to "name"

Returns:

  •   Collection The original Collection object

The following example creates then removes elements from the collection:

var collection = new Collection([1, 2, 3, 4, 5]);
collection
	.list()
	.remove([1, 3, 5])
	.list();
[object Collection length=5]: Array (depth:1, objects:0, values:5, time:0.0 seconds)
------------------------------------------------------------------------------------
array => Array
	 0: 1
	 1: 2
	 2: 3
	 3: 4
	 4: 5


[object Collection length=2]: Array (depth:1, objects:0, values:2, time:0.0 seconds)
------------------------------------------------------------------------------------
array => Array
	 0: 2
	 1: 4

You can also remove elements from the collection in exactly the same way as the find() method works to identify elements to remove.

The following example, first selects all elements on the stage, then removes only the stars:

var collection = new Collection(starsAndSquares);
collection
	.list('All elements')
	.remove('star*')
	.list('Squares only');
All elements: Array (depth:1, objects:0, values:8, time:0.0 seconds)
--------------------------------------------------------------------------------
array => Array
	 0: "name: star4"
	 1: "name: star3"
	 2: "name: star2"
	 3: "name: star1"
	 4: "name: square4"
	 5: "name: square3"
	 6: "name: square2"
	 7: "name: square1"


Squares only: Array (depth:1, objects:0, values:4, time:0.0 seconds)
--------------------------------------------------------------------------------
array => Array
	 0: "name: square4"
	 1: "name: square3"
	 2: "name: square2"
	 3: "name: square1"

filter(callback, thisObject)

Filters the collection using a callback function

Parameters:

  • callback Function Function to test each element of the array
  • thisObject Object Object to use as this when executing callback

Returns:

  •   Collection The original Collection object

The following example filters out any elements with the letter "w" in them:

var collection = new Collection(['one', 'two', 'three']);
collection
    .filter( function(element){ return element.indexOf('w') == -1; } )
    .list();
[object Collection length=2]: Array (depth:1, objects:0, values:2, time:0.0 seconds)
------------------------------------------------------------------------------------
array => Array
	 0: "one"
	 1: "three"

Editing Methods

The editing methods allow you to update the properties of elements in the collection.

attr(name, value)

Modifies a particular attribute on all items in the collection

Parameters:

  • prop Object An object containing name:value pairs of attribute to modify
  • prop String The name of the attribute to modify
  • value Value A value attribute value
  • value Function A callback function that returns a value, of the format function(element, index, elements);

Returns:

  •   Collection The current Collection

As this method modifies the properties of objects, stage elements will be used instead of strings for the examples. Before running the examples, create or drag some movieclip instances into random positions on the stage.

The following example modifies the "y" property of selected elements to position them 100px from the top:

var collection = new Collection($selection);
collection.attr('y', 100);

The following example modifies 2 properties at the same time, using an Object of named values:

var collection = new Collection($selection);
collection.attr( {'y':100, rotation:45} );

The following example modifies the "x" property of selected elements, using a callback function to position them sequentially from left to right on stage:

var collection = new Collection($selection);
collection.attr( 'x', function(element, index, elements){ return index * 100; } );

A similar result could also be achieved using each():

var collection = new Collection($selection);
collection.each( function(element, index, elements){ element.x = index * 100; } );

Utility Methods

The utility methods allow you to

sort()

Sorts the internal elements of a collection

Returns:

  •   Collection The original Collection object

The following example sorts the collection:

var collection = new Collection([5, 4, 3, 2, 1]);
collection
    .list()
    .sort()
    .list();
Unsorted: Array (depth:1, objects:0, values:5, time:0.0 seconds)
--------------------------------------------------------------------------------
array => Array
	 0: 5
	 1: 4
	 2: 3
	 3: 2
	 4: 1


Sorted: Array (depth:1, objects:0, values:5, time:0.0 seconds)
--------------------------------------------------------------------------------
array => Array
	 0: 1
	 1: 2
	 2: 3
	 3: 4
	 4: 5

 

list()

Utility function to list the contents of the collection

Returns:

  •   Collection The original Collection object

The following example lists the contents of a collection:

new Collection(['one', 'two', 'three']).list();
[object Collection length=2]: Array (depth:1, objects:0, values:2, time:0.0 seconds)
------------------------------------------------------------------------------------
array => Array
	 0: "one"
	 1: "two"
	 2: "three"

call(callback, ...params)

A chainable utility function to call an external callback function a single time

Parameters:

  • callback Function Function to call
  • ...params Parameters Additional parameters passed after the first argument

Returns:

  •   Collection The original Collection object

The call() method allows you to call a single arbitrary function as part of a chain of commands. The function could be one of your own custom functions, or even a method on the current collection should you see fit. Function parameters are added after the callback reference as additional mthod arguments.

The following example calls the native trace function, passing in the collection's elements, then calls an additional collection method, simply to demonstrate chaining:

var collection = new Collection(['one', 'two', 'three']);
var value = collection
    .call(trace, collection.elements)
    .get(0);

trace(value);
one,two,three
one

apply(callback, params, scope)

A chainable utility function to call an external callback function a single time

Parameters:

  • callback Function Function to call
  • params Array Optional arguments to be passed to the callback
  • scope Object An optional scope to run the function in, default to the collection

Returns:

  •   Collection The original Collection object

The apply() method has exactly the same function as the call() method, allowing you to call a single function as part of a chain of commands, but passes the callback parameters as an Array, an optionally allows you to set the scope of the call as well.

The following example calls a trace method on an object, the first scoped to the collection (by default) and the second scoped to the object:

var obj =
{
	elements:['x', 'y', 'z'],
	trace:function(a, b)
	{
		trace(a, b, this.elements);
	}
}

var collection = new Collection(['one', 'two', 'three']);

var value = collection
    .apply(obj.trace, ['a', 'b']) // will trace the collection's elements
    .apply(obj.trace, ['a', 'b'], obj) // will trace obj's elements
    .get(0);

trace(value);
a, b, one,two,three
a, b, x,y,z
one

toString()

Return a string representation of the collection

Returns:

  •   String A string representation of the collection

The following example demonstrates the result of tracing a collection:

var collection = new Collection(['one', 'two', 'three']);
trace(collection);
[object Collection length=3]

One Response to Collection (class)

  1. Chris says:

    The example for the “each()” method is actually using “reach()”