ElementCollection (class)

Categories:Elements

Overview

Summary

The ElementCollection class is designed to group and manipulate elements on the Flash stage.

It is a subclass of the Collection class, background information about which can be found in the Introduction to Collections article.

Contents

Usage

The ElementCollection class expects an array of stage elements as its only parameter, so is nearly always used in conjunction with the Element Selector function (although you can of course pass in elements manually). This allows you to abstract fairly complex selections into an easy-to-manage expressions.

The following example creates an ElementCollection using standard dom properties:

var collection = new ElementCollection($selection);
collection.list();
[object ElementCollection length=5]: Array (depth:1, objects:0, values:12, time:0.0 seconds)
--------------------------------------------------------------------------------------------
array => Array
	 0: "Item_12"
	 1: "Item_13"
	 2: "Item_14"
	 3: "Item_15"
	 4: "Item_16"

The following example uses the Element Selector function to grab the current stage selection:

var collection = $(':selection');
collection.list();
[object ElementCollection length=5]: Array (depth:1, objects:0, values:12, time:0.0 seconds)
--------------------------------------------------------------------------------------------
array => Array
	 0: "Item_12"
	 1: "Item_13"
	 2: "Item_14"
	 3: "Item_15"
	 4: "Item_16"	

Note that a collection does not select the items on the stage - it merely holds a reference to them. To physically select items on the stage, see the select() method.

ElementCollection extends Collection

One last note - remember that ElementCollection extends Collection, so you still get to use all the methods on the Collection class, including each(), which is a very powerful method for applying custom manipulation to collection elements:

See the example in Working with Elements for more infomation.

Running the example code

If you want some elements to to quickly test the example code on this page, run the following code which will create some transparent red squares on the Flash stage:

function makeSquares(num, cols)
{
	// variables
		num = num || 9;
		cols = cols || 3;
		var dom = window.dom;
		var lib = dom.library;
		var context = Context.create();

	// make square
		if( ! lib.itemExists('square'))
		{
			lib.addNewItem('movie clip', 'square');
			lib.editItem('square');
			dom.addNewRectangle({left:-25, top:-25, right:25, bottom:25}, 0);
			dom.selectAll();
			dom.setFillColor('#FF000066');
			dom.setStroke('#000000', 0.5, 'solid')
			context.goto();
		}

	// add items to scene
		var collection = $('*');
		for(var i = 0; i

API

ElementCollection(elements, dom)

ElementCollection class enacpsulates and modifies Arrays of stage Elements

Parameters:

  • elements Array An Array of Stage Elements
  • elements Element A single Stage Element
  • dom Document An optional Document instance. Defaults to the current Document

Returns:

  •   Collection The original ElementCollection object

The following example grabs all items on the stage:

var collection = $('*');
collection.list();
[object ElementCollection length=10]: Array (depth:1, objects:0, values:10, time:0.0 seconds)
---------------------------------------------------------------------------------------------
array => Array
	 0: "Item_01"
	 1: "Item_02"
	 2: "Item_03"
	 3: "Item_04"
	 4: "Item_05"
	 5: "Item_06"
	 6: "Item_07"
	 7: "Item_08"
	 8: "Item_09"
	 9: "Item_10"		

Properties

items

Returns an ItemCollection of the collection's elements

  • Type: ItemCollection
  • Access: Read

The items property gives you direct access to the Library Items that are used in the current collection, by way of an ItemCollection.

The following example first lists the current elements, then lists and reveals the corresponding Library Items in the Library panel:

$($selection)  // create the collection
	.list()    // list the elements
	.items     // return an ItemCollection from the ElementCollection
	.list()    // list the items
	.reveal(); // and finally, reveal them in the Library
[object ElementCollection length=9]: Array (depth:1, objects:0, values:9, time:0.0 seconds)
-------------------------------------------------------------------------------------------
array => Array
	 0: "name: square1"
	 1: "name: square2"
	 2: "name: star1"
	 3: "name: star2"
	 4: "name: triangle1"
	 5: "name: square3"
	 6: "name: star3"
	 7: "name: circle4"
	 8: "name: square4"


[object ItemCollection length=4]: Array (depth:1, objects:0, values:4, time:0.0 seconds)
----------------------------------------------------------------------------------------
array => Array
	 0: "2 - elements/shapes/square"
	 1: "2 - elements/shapes/star"
	 2: "2 - elements/shapes/triangle"
	 3: "2 - elements/shapes/circle

 

Inherited members

ElementCollection is a subclass of the Collection class:

Standard methods

select(element)

Select one or all of the elements within the collection

Parameters:

  • element Boolean An optional true flag to select all elements (the default)
  • element Number An optional index of the element to select
  • element String An optional name of the element to select
  • element Element An optional reference to the element to select

Returns:

  •   ElementCollection The original ElementCollection object

The following example selects all (unlocked) items on the stage:

$('*').select();

The following example selects the item named "Item_03" in the collection:

$('*').select('Item_05');

The following example selects each of the items in turn, and alerts its progress:

function select(element, index)
{
	this.select(index);
	alert('Selected ' + element.name)
}
$('*').each(select);

Manipulation methods

The manipulation methods add or remove items from the collection.

duplicate(add)

Duplicates and updates the current collection

Parameters:

  • add Boolean An optional flag to add (rather then replace) the duplicated items to the current collection, defaults to false

Returns:

  •   ElementCollection The original ElementCollection object

The following example creates some squares, then chains up duplicate and move commands to create an array of elements:

makeSquares(5, 5);

$('*')
	.space('horizontal', 10)
	.move(10, 10)
	.duplicate()
	.move(0, 60, true)
	.duplicate()
	.move(0, 60, true)

Note that new items are automatically renamed from their existing names and numbers. In the above example, the newly-duplicated items were labeled based on from the highest-numbered item in the previous element, Item_05, creating Item_06 through to Item_15.

deleteElements()

Removes all elements from the collection and the stage

Returns:

  •   ElementCollection The original ElementCollection object

The following example deletes the selected elements:

$(':selected').deleteElements();

 

Translation methods

The translation methods modify the geometry of the elements, either as a whole, or indivdually.

move(x, y, relative)

Move the collection on stage by, or to, x and y values

Parameters:

  • x Number The x pixel value to move to, or by
  • y Number The y pixel value to move to, or by
  • relative Boolean An optional flag to move the elements relative to their current position, defaults to false

Returns:

  •   ElementCollection The original ElementCollection object

The following example moves all elements of the collection, as a whole unit, to the top-left hand corner of the stage, with the bounding box of the collection aligned to the [0,0] point:

$('*').move(0, 0);

rotate(angle, whichCorner)

Rotates the collection by a specified number of degrees

Parameters:

  • angle Number A floating-point value that specifies the angle of the rotation
  • whichCorner String An optional String that specifies which side of the bounding box to rotate. Acceptable values are "top right", "top left", "bottom right", "bottom left", "top center", "right center", "bottom center", and "left center"

Returns:

  •   ElementCollection The original ElementCollection

Note that the rotate method currently uses Flash's rotateSelection() method, so will select the elements before rotating them. This may change in a later release.

The following example rotates the current selection by 45 degrees:

$($selection).rotate(45);

scale(xScale, yScale, whichCorner)

Scales the collection by a specified amount

Parameters:

  • xScale Number A floating-point value that specifies the amount of x by which to scale
  • yScale Number A floating-point value that specifies the amount of y by which to scale
  • whichCorner String An optional String that specifies which side of the bounding box to rotate. Acceptable values are "top right", "top left", "bottom right", "bottom left", "top center", "right center", "bottom center", and "left center"

Returns:

  •   ElementCollection The original ElementCollection

Note that the scale method currently uses Flash's scaleSelection() method, so will select the elements before scaling them. This may change in a later release.

The following example scales the current selection by 50%:

$($selection).scale(0.5, 0.5);

centerTransformPoint(state)

Centers the transform points of the elements

Parameters:

  • state Boolean Sets the transform point to the center (true) or the original pivot point (false). Defaults to true

Returns:

  •   ElementCollection The original ElementCollection object

The following example centers the transform point of the current selection:

$($selection).centerTransformPoint();

resetTransform()

Resets the transform of the elements

Returns:

  •   ElementCollection The original ElementCollection object

The following example rotates the stage elements, then after the alert, clears the transformation:

$('*')
	.attr('rotation', 45)
	.call(alert, 'Click OK to reset transform')
	.resetTransform();

Attribute methods

The attribute methods modify some attribute, or group of attributes of each of the elements.

attr(name, value)

Sets a single property on each element in the collection

Parameters:

  • prop Object A hash of valid name:value properties
  • prop String The name of the property to modify
  • value Value A valid property value
  • value Array An array of property values
  • value Object An Object of x, y property values
  • value Function A callback function of the format function(element, index, elements), that returns a value

Returns:

  •   ElementCollection The original ElementCollection object

The attr() method is identical to the Collection attr() method with the subtle difference that it supports the following compound pseudo-properties:

  • position [x, y] x and y in stage coordinatesy
  • scale [scaleX, scaleY] Pass in a single number to set scale for both axis
  • size [width, height] Sets the width and height in stage (not element) space, so will skew the object if rotated

You can supply either a single Number to copy the value to both components (ie, scaleX and scaleY), and Array of 2 values, or an object with x and y properties.

Note that attr() also handles alpha, tint, and brightness, but you need to select() the elements first. See the nth() example on the Selectors page for more info.

The following example sets the rotation property of all objects:

$('*').attr('rotation', 30);

The following example sets the x and y scale of all the objects:

$('*').attr('scale', [1, 0.5]);

The following 2 examples update 2 properties at the same time, as well as using a callback, to set a random position on the collection's elements:

function rand(){ return Math.random() * 200 - 100; } // function is called twice
$('*').attr({x:rand, y:rand});	
function rand(){ return [Math.random() * 200, Math.random() * 200]; } // function passes back a 2-element array
$('*').attr('position', rand);

This example sets the scale of an object using a compound property name (scale) but passes back only a single value, which is set for both components (scaleX & scaleY):

function rand(){ return Math.random() + 0.5; }

$('*').attr('scale', rand);


rename(baseName, startIndex, padding, separator)

Numerically renames elements in order

Parameters:

  • baseName Function A callback of the format function(item, index, items, originalName) which should return a String name

  • baseName String A single "name_###" name/number pattern string

  • baseName String The basename for your objects
  • padding Number An optional padding length for the numeric part of the name
  • padding Boolean An optional flag to automatically pad the numeric part of the name to the correct length
  • startIndex Number An optional number to start renaming from. Defaults to 1
  • separator String An optional separator between the numeric part of the name. Defaults to '_'

Returns:

  •   ItemCollection The original ItemCollection

The following example performs a default rename, renaming all items on the stage from the starting index "1" padding as necessary:

$('*')
	.rename()
	.list();
[object ElementCollection length=10]: Array (depth:1, objects:0, values:10, time:0.0 seconds)
---------------------------------------------------------------------------------------------
array => Array
	 0: "Item_01"
	 1: "Item_02"
	 2: "Item_03"
	 3: "Item_04"
	 4: "Item_05"
	 5: "Item_06"
	 6: "Item_07"
	 7: "Item_08"
	 8: "Item_09"
	 9: "Item_10"

The following examples demonstrate various renaming techniques:

var items = $(':selection');
items.rename(); // rename using defaults, "clip_1", "clip_2", "clip_3" ... items.rename('clip_##'); // rename, starting from 1, padding to 2 characters, "clip_01", "clip_02", "clip_03" ... items.rename('clip_025'); // rename, starting from 25, padding to 3 characters, "clip_025", "clip_026", "clip_027" ... items.rename('clip', 4, 25); // rename, starting from 25, padding to 4 characters, "clip_0025", "clip_0026", "clip_0027" ...

The following example uses a callback to rename any symbols on stage with their class name:

$$(':symbol').rename( function(element){ return element.libraryItem.linkageClassName.split('.').pop(); } );

orderBy(prop, reverseOrder)

Reorder the elements on the stage (front-to-back) by an arbitrary property

Parameters:

  • prop String The property to compare
  • prop Function A sort function of the format function(a, b){ } which reurns 1, 0, or -1;
  • reverseOrder Boolean Optionally arrange in reverse order

Returns:

  •   ElementCollection The original ElementCollection object

The following example positions, scales, then orders elements in reverse order by size, a pseudo-property derived from width x height (note that orderBy() also reorders the elements within the internal Array, which will affect subsequent operations):

$('*')
	.resetTransform()
	.attr('pos', 125)
	.attr('scale', function(element, index, elements){ return index / elements.length * 5; })
    .orderBy('size', true);

align(props)

Align elements to one another

Parameters:

  • props String The specific arguments for the arrange type. Acceptable values are 'left,right,top,bottom,top left,top right,bottom left,bottom right,vertical,horizontal,center'

Returns:

  •   ElementCollection The original ElementCollection object

The align() method repackages the native Flash align functionaliity, with a slightly different parameter syntax. Note that align() will soon support aligning to objects, similar to match();

The following example creates and scales some :

$('*')
	.resetTransform()
	.randomize({'pos':300, scale:2, rotation:360})
	.align('top')


distribute(props, toStage)

Distribute elements relative to one another

Parameters:

  • props String 1 or 2 of 'left,horizontal,right,top,vertical,bottom'
  • toStage Boolean Use the stage bounding box

Returns:

  •   ElementCollection The original ElementCollection object

The distribute() method repackages the native Flash distribute functionaliity, with a slightly different parameter syntax.

The following example positions, randomizes, then distributes elements horizontally:

$('*')
	.attr('pos', 30)
	.randomize({x:400, width:[5, 40]})
	.attr('height', function(e){return e.width})
	.distribute('horizontal')


space(direction, type)

Space elements relative to one another

Parameters:

  • direction String The direction in which to space. Acceptable values are 'vertical,horizontal'
  • type Number An optional amount of space to add or subtract between items
  • type Boolean An optional flag to use the stage bounding box (only has an effect on the root)

Returns:

  •   ElementCollection The original ElementCollection object

The distribute() method repackages the native Flash space functionaliity, with a slightly different parameter syntax.

The following example positions, randomizes, then distributes elements horizontally in a few different ways:

$('*')
	.attr('pos', 30)
	.randomize({x:400, width:[5, 40]})
	.attr('height', function(e){return e.width})

	.space('horizontal')        // spaces according to the current collection bounds
	.space('horizontal', 0)     // spaces left-to-right, with a 0px gutter
	.space('horizontal', true); // spaces to the document bounds (only effective on the root)	


match(prop, element)

match elements' dimensions relative to one another

Parameters:

  • props String The dimension in which to match. Acceptable values are'width,height,size'
  • element Boolean An optional flag (true=biggest, false=smallest) of the element whose dimension(s) you want to match. Defaults to true
  • element Number An optional index of the element whose dimension(s) you want to match
  • element String An optional name of the element whose dimension(s) you want to match
  • element Element An optional reference to an element (which doesn't need to be in the collection) whose dimension(s) you want to match

Returns:

  •   ElementCollection The original ElementCollection object

The match() method adds to JSFL's native match functionality by allowing you to choose how element sizes are matched, with a slightly different syntax from the native method.

The following example applies the default match (equivilent to passing true as the 2nd parameter) which is to match to the largest size:

$('*')
	.randomize('rotation', 360)
	.match('size', 0)

The following example chooses another element within the collection to match the height to:

$(squares)
	.randomize({size:50, y:'20'})
	.match('height', circle);


toGrid(precision, rounding)

Repositions element positions to round multiples of numbers

Parameters:

  • precision Number The pixel-precision to reposition to, e.g. 0
  • precision Array The pixel-precision to reposition to, e.g. [10, 20]
  • rounding Number Round down(-1), nearest(0), or up(1). Defaults to nearest(0)

Returns:

  •   ElementCollection The original ElementCollection object

The following example aligns all elements to the grid:

$('*').toGrid(0);

The following example creates some squares, randomizes them, then snaps them to the nearest 25 pixels:

makeSquares(3 * 6, 6);
$('*')
	.randomize({pos:25})
	.toGrid(25);

The following example uses the Iterators class to align all elements in all library items, across all layers and frames, to the closest pixel:

function alignElements(frame, index, frames, context)
{
	trace('Aliging elements in: ' + context);
	$('*').toGrid(0);
}
Iterators.items(true, null, null, alignElements);
Aliging elements in: [object Context dom="library items 02.fla" timeline="Button 2" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="Button 3" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 1" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 1" layer[0]="Layer 1" keyframe[1]=3]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 1" layer[0]="Layer 1" keyframe[2]=8]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 1" layer[1]="Layer 2" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 1" layer[2]="Layer 3" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 1" layer[2]="Layer 3" keyframe[1]=3]
Aliging elements in: [object Context dom="library items 02.fla" timeline="Sprite 1" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="Button 1" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="Graphic 1" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="Graphic 2" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="Sprite 2" layer[0]="Layer 1" keyframe[0]=0]
Aliging elements in: [object Context dom="library items 02.fla" timeline="MovieClip 3" layer[0]="Layer 1" keyframe[0]=0]
	

randomize(prop, value)

Randomizes properties of the elements

Parameters:

  • prop Object An object containing property name:value pairs
  • prop String A valid String property. Acceptable values are: x, y, width, height, rotation, scaleX, scaleY, transformX, transformY, skewX, skewY, position, scale, size. Note that position, scale and size should be arrays
  • value Number A multiplier value, i.e. 10
  • value String A valid modifier property, i.e. "+20%"
  • value Array A valid modifier range, i.e. [100, 200]

Returns:

  •   ElementCollection The original ElementCollection object

The randomize() method allows you to randomize the properies of elements by passing numbers, expressions, and ranges as the methods's 2nd argument (see xjsfl.utils.randomizeValue() for more information):

  • Numeric 25 0 - 25 more than the original value
  • Expression "25" 0 - 25 on either side of the original value
  • Percentage "+25%" 100% - 125% of the original value
  • Range [25, 50] Anywhere between 25 - 50
You may also pass in a single Object of property:value pairs, to update multiple properties at once. Note that randomize() does not yet support pseudo properties such as tint, brightness and color.

The following example creates some elements, then randomizes various properties using a variety of techniques:

makeSquares(3 * 6, 6);
$('*')
	.attr('x', function(e){ return e.x * 2; })
	.randomize({
		pos:100,
		size:[60, 10],
		rotation:'180',
		scale:'150%'
	});

Editing methods

exec(callback, params, scope)

Enters edit mode for each symbol item in the collection, executing a user-supplied function within each one

Parameters:

  • callback Function A function with a signature matching function(element, index, ...params), with "this" referring to the original ItemCollection
  • params Array An array of optional parameters to pass to the callback
  • scope Object An optional scope to call the method in

Returns:

  •   ItemCollection The original ItemCollection

The following example loops over the current selection, and enters edit mode for each Item, fires an alert box, then eventually returns to the original Document context:

function callback(element, index, param1)
{
	alert(param1 + ' We are now in element ' +index+ ' called "' + element.name + '"');
}

var collection = $($selection);
collection.exec(callback, 'Hello there!');

This allows you to run custom code within each Library Item without losing your place in the document:

Utility methods

refresh()

Forces the a refreshes of the display after a series of operations

Returns:

  •   ElementCollection The original ElementCollection object

Sometimes after a series of element updates, the stage doesn't update. The refresh() method forces an update.

The following example refreshes the stage after a hypothetical operation that leaves the stage in an invalid state:

$('*')
	.each(someOperation)
	.refresh();

Comments are closed.