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(dom.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);
Selection

Some collection types also have selector functions in order to return customised Collections in one line of code:

$$(':bitmap')
    .rename('Bitmap')
    .attr('allowSmoothing', true);	

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

API - methods

The following methods provide core functionality for all the Collection classes. As such, each of the examples on this page will 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]

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

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

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

remove(startIndex, deleteCount)

Removes elements from the collection

Parameters:

  • startIndex Number An integer that specifies at what position to remove elements
  • deleteCount Number An option number of elements to be removed, defaults to 1

Returns:

  •   Collection The original Collection object

The following example removes the second element in the collection:

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


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

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"

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

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(dom.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(dom.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(dom.selection);
collection.attr( 'x', function(element, index, elements){ return index * 100; } );

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

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

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

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"

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]	

API - properties

elements

The internal elements of the collection

  • Type: Array
  • Access: Read

Th 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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>