I am working with Flex 4.6 AIR application. I have a tile list and there is an image as an itemRenderer. When i search images, the data is not filtered but is selected the indices(selected items) of the tilelist and i set a custom property in arrayCollection(dataProvider) then updateDisplayList called and i start a timer in this function. Which perform play the inner images in the selected item.
Now the problem is when if i search the item and click the non selected item the timer is not stoped. How can i achieve that.
The code of itemRenderer is below
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
autoDrawBackground="true" buttonMode="true"
click="itemrenderer2_clickHandler(event)"
doubleClick="itemrenderer1_doubleClickHandler(event)" doubleClickEnabled="true"
rightClick="itemrenderer1_rightClickHandler(event)"
rollOut="itemrenderer1_rollOutHandler(event)"
rollOver="itemrenderer1_rollOverHandler(event)" useHandCursor="true">
<fx:Script>
<![CDATA[
import customs.customcomponents.LibraryReDownloadComponent;
import customs.customcomponents.VideoUploadBox;
import dbconnection.Connection;
import globalData.DataModel;
import mx.collections.ArrayCollection;
import mx.core.FlexGlobals;
import mx.core.UIComponent;
import mx.events.ItemClickEvent;
import mx.managers.PopUpManager;
import mx.utils.ObjectProxy;
import mx.utils.UIDUtil;
private var isLoaded:Boolean = false;
private var timer:Timer;
private var rollOverFlag:Boolean = false;
private var countThumb:int = 0;
private var arrThumnail:ArrayCollection;
private var loaderThumb:Loader;
private var request:URLRequest;
private var requestThumb:URLRequest;
private var loader:Loader;
private var sqlStatStatus:SQLStatement;
private var downloadVideoPath:String = "";
private var videoUrlStream:URLStream;
private var videoFileStream:FileStream;
private var uploadvidbox:VideoUploadBox = new VideoUploadBox();
private var dtStartVideo:Date;
private var videoFileName:String = "";
private var videoFile:File;
private var IsRollOver:Boolean = false;
[Bindable]
private var modellocator:DataModel=DataModel.getInstance();
private var connection:Connection = Connection.getInstance();
override public function set data(value:Object):void
{
if(value != null)
{
super.data = value;
if(timer != null)
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
timer = null;
}
loaderThumb = new Loader();
rollOverFlag = false;
countThumb = 0;
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
requestThumb = new URLRequest("file://" + data.Videothumbnail);
}
else
{
requestThumb = new URLRequest(data.Videothumbnail);
}
loaderThumb.contentLoaderInfo.addEventListener(Event.COMPLETE,onThumbComplete);
loaderThumb.load(requestThumb);
if(data.VideoBuyFlag == "yes")
{
if(data.VideoIsDeleted == "No")
{
bContain.setStyle("borderColor", "#00FF18");
bContain.alpha = 1;
}
else
{
bContain.setStyle("borderColor", "#888888");
bContain.alpha = 0.3;
}
}
else
{
if(data.VideoIsDeleted == "No")
{
bContain.setStyle("borderColor", "#C50000");
bContain.alpha = 1;
}
else
{
bContain.setStyle("borderColor", "#888888");
bContain.alpha = 0.3;
}
}
if(data.VideoStatus == "Active")
{
imgActive.source = "assets/btn_Active.jpg";
bContain.alpha = 1;
}
else
{
imgActive.source = "assets/btn_InActive.jpg";
bContain.alpha = 0.3;
}
arrThumnail = new ArrayCollection();
if(data.Videothumbdata.thumbimage != null)
{
if(data.Videothumbdata.thumbimage.source.item.length > 1)
{
for(var i:int = 0; i < data.Videothumbdata.thumbimage.source.item.length; i++)
{
arrThumnail.addItem(data.Videothumbdata.thumbimage.source.item[i]);
}
}
else
{
arrThumnail.addItem(data.Videothumbdata.thumbimage.source.item);
}
}
}
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
/* trace(data.Videoname);
trace("IsRollOver : " + IsRollOver.toString());
trace("IsSearching : " + data.IsSearching.toString());
trace("rollOverFlag : " + rollOverFlag.toString()); */
if(data.IsSearching == false)
{
if(IsRollOver == false)
{
if(timer != null)
{
trace("inner");
loaderThumb = new Loader();
rollOverFlag = false;
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
requestThumb = new URLRequest("file://" + data.Videothumbnail);
}
else
{
requestThumb = new URLRequest(data.Videothumbnail);
}
loaderThumb.contentLoaderInfo.addEventListener(Event.COMPLETE,onThumbComplete);
loaderThumb.load(requestThumb);
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
countThumb= 0;
System.gc();
System.gc();
}
}
}
else
{
if(rollOverFlag == false)
{
rollOverFlag = true;
trace("Hi");
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, showFrame);
timer.start();
}
else
{
if(timer != null)
{
trace("SecondInner");
loaderThumb = new Loader();
rollOverFlag = false;
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
requestThumb = new URLRequest("file://" + data.Videothumbnail);
}
else
{
requestThumb = new URLRequest(data.Videothumbnail);
}
loaderThumb.contentLoaderInfo.addEventListener(Event.COMPLETE,onThumbComplete);
loaderThumb.load(requestThumb);
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
countThumb= 0;
System.gc();
System.gc();
}
}
}
}
protected function showFrame(event:TimerEvent):void
{
var file:File;
trace("hello");
if(countThumb < arrThumnail.length)
{
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
file = new File("file://" + arrThumnail[countThumb]);
}
else
{
file = new File(arrThumnail[countThumb]);
}
if(file.exists)
{
loader = new Loader();
if(flash.system.Capabilities.os.indexOf("Mac") > -1)
{
request=new URLRequest("file://" + arrThumnail[countThumb]);
}
else
{
request=new URLRequest(arrThumnail[countThumb]);
}
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
loader.load(request);
if(countThumb == (arrThumnail.length - 1))
{
countThumb = 0;
}
else
{
countThumb++;
}
}
else
{
countThumb++;
}
}
else
{
countThumb = 0;
}
}
protected function itemrenderer1_rollOverHandler(event:MouseEvent):void
{
if(data.IsSearching == false)
{
rollOverFlag = true;
IsRollOver = true;
if(arrThumnail != null && arrThumnail.length > 0)
{
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, showFrame);
timer.start();
}
}
}
private function onComplete(event:Event):void
{
if(rollOverFlag)
{
imgThumb.source = loader;
}
}
private function onThumbComplete(event:Event):void
{
imgThumb.source = loaderThumb;
}
protected function itemrenderer1_rollOutHandler(event:MouseEvent):void
{
if(data.IsSearching == false)
{
rollOverFlag = false;
IsRollOver = false;
imgThumb.source = loaderThumb;
if(timer != null)
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, showFrame);
timer = null;
}
countThumb = 0;
System.gc();
System.gc();
}
}
protected function itemrenderer2_clickHandler(event:MouseEvent):void
{
for(var i:int=0; i < modellocator.libraryvideoac.length; i++)
{
modellocator.libraryvideoac[i].IsSearching = false;
}
parentDocument.parentDocument.txt_search.text = resourceManager.getString('languages','lblSearchText');
parentDocument.parentDocument.unCheckSelection();
if(data.VideoIsDeleted == "Yes")
{
var popupReDownload:LibraryReDownloadComponent = new LibraryReDownloadComponent();
popupReDownload = PopUpManager.createPopUp(UIComponent(this.parentApplication), LibraryReDownloadComponent, true) as LibraryReDownloadComponent;
popupReDownload.addEventListener("downloadMovie", redownloadMovie);
PopUpManager.centerPopUp(popupReDownload);
}
}
]]>
</fx:Script>
<fx:Declarations>
<mx:NumberFormatter id="numFormat" precision="2"/>
</fx:Declarations>
<s:BorderContainer id="bContain" left="2" top="2" width="92" height="67" backgroundAlpha="1"
backgroundColor="#000000" borderColor="#030304" borderWeight="3">
<s:Image id="imgThumb" width="86" height="61" fillMode="scale" scaleMode="stretch"/>
<s:Image id="imgActive" right="0" bottom="0" width="15" height="15" buttonMode="true"
useHandCursor="true"/>
</s:BorderContainer>
</s:ItemRenderer>
You have timer instantiation at different places in the code. I can't be sure of the actual program flow, but maybe you instantiate the timer two times? In that case program would overwrite the timer variable, and lose reference to the first timer. So, when you call timer.stop() you actually only stop one timer, while the other keeps running in the background.
You didn't set weak reference attribute here:
timer.addEventListener(TimerEvent.TIMER, showFrame);
so the timer will not be garbage collected if you lose its reference (even if you call System.gc() twice :-)). Check that situation out, and try adding a listener with:
timer.addEventListener(TimerEvent.TIMER, showFrame, false, 0, true);
Related
I use a multiple-check Drop-Down which does not trigger the first Change event. Subsequent events trigger properly. When I select Select All or any other option the first time it does not trigger the event either.
use namespace mx_internal;
[Style(name="selectAllBorderAlpha", type="Number", inherit="no", theme="spark, mobile", minValue="0.0", maxValue="1.0")]
[Style(name="selectAllBorderColor", type="uint", format="Color", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBorderVisible", type="Boolean", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBackgroundColor", type="uint", format="Color", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBackgroundAlpha", type="Number", inherit="no", theme="spark, mobile", minValue="0.0", maxValue="1.0")]
[IconFile("DropDownList.png")]
[DiscouragedForProfile("mobileDevice")]
public class CheckBoxDropDownList extends CheckBoxDropDownListBase
{
public function CheckBoxDropDownList()
{
super();
addEventListener(IndexChangeEvent.CHANGE, indexChangeHandler);
}
protected function indexChangeHandler(event:IndexChangeEvent):void
{
selectedAll = false;
}
[SkinPart(required="false")]
public var selectAllCheckBox:CheckBox;
[SkinPart(required="false")]
public var selectAllHitArea:UIComponent;
[SkinPart(required="false")]
public var labelDisplay:IDisplayText;
private var labelChanged:Boolean = false;
private var labelDisplayExplicitWidth:Number;
private var labelDisplayExplicitHeight:Number;
private var sizeSetByTypicalItem:Boolean;
override public function get baselinePosition():Number
{
return getBaselinePositionForPart(labelDisplay as IVisualElement);
}
private var _prompt:String = "";
[Inspectable(category="General", defaultValue="")]
public function get prompt():String
{
return _prompt;
}
public function set prompt(value:String):void
{
if (_prompt == value)
return;
_prompt = value;
labelChanged = true;
invalidateProperties();
}
[Inspectable(category="Data")]
override public function set typicalItem(value:Object):void
{
super.typicalItem = value;
invalidateSize();
}
override protected function commitProperties():void
{
super.commitProperties();
if (labelChanged)
{
labelChanged = false;
updateLabelDisplay();
}
if (selectedAllChanged)
{
selectedAllChanged = false;
if (selectAllCheckBox)
{
selectAllCheckBox.selected = _selectedAll;
this.dispatchEvent(new Event("selectAllChanged"));
}
invalidateList();
}
}
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == labelDisplay)
{
labelChanged = true;
invalidateProperties();
}
if (instance == selectAllCheckBox)
{
selectedAllChanged = true;
invalidateProperties();
}
if (instance == selectAllHitArea)
{
selectAllHitArea.addEventListener(MouseEvent.CLICK, selectAllHitArea_clickHandler);
}
}
override protected function partRemoved(partName:String, instance:Object):void
{
super.partRemoved(partName, instance);
if (instance == selectAllHitArea)
{
selectAllHitArea.removeEventListener(MouseEvent.CLICK, selectAllHitArea_clickHandler);
}
}
protected function selectAllHitArea_clickHandler(event:MouseEvent):void
{
if (selectAllCheckBox)
selectedAll = !selectAllCheckBox.selected;
}
private var _selectedAll:Boolean = false;
private var selectedAllChanged:Boolean;
public function get selectedAll():Boolean
{
return _selectedAll;
}
public function set selectedAll(value:Boolean):void
{
if (value == _selectedAll)
return;
_selectedAll = value;
selectedAllChanged = true;
labelChanged = true;
selectedIndices = Vector.<int>([]);
//setSelectedItem(undefined, false);
invalidateProperties();
}
public function setSelectedIndices(selValues:Array):void
{
if (this.dataProvider == null) {
return;
}
var selIndices:Vector.<int> = new Vector.<int>();
if (selValues == null || selValues.length == 0)
{
this.selectedAll = true;
return;
}
for(var i:int=0; i < this.dataProvider.length; i++)
{
for(var j:int=0; j < selValues.length; j++)
{
var obj:Object = this.dataProvider.getItemAt(i);
if(selValues[j] == obj.value || selValues[j] == obj.label)
{
selIndices.push(i);
break;
}
}
}
if (selIndices.length == 0)
{
this.selectedAll = true;
}
else
{
this.selectedAll = false;
this.selectedIndices = selIndices;
}
}
override protected function item_mouseDownHandler(event:MouseEvent):void
{
if (selectedAll)
{
selectedAll = false;
var newIndex:int
if (event.currentTarget is IItemRenderer)
newIndex = IItemRenderer(event.currentTarget).itemIndex;
else
newIndex = dataGroup.getElementIndex(event.currentTarget as IVisualElement);
var arr:Array = dataProvider.toArray()
arr.splice(newIndex, 1);
selectedItems = Vector.<Object>(arr);
return;
}
super.item_mouseDownHandler(event);
// if all items are selected, then unselect them and check the "Select All" checkbox.
if (selectedItems.length == dataProvider.length)
{
selectedAll = true;
selectedIndex = -1;
}
}
override protected function dropDownController_closeHandler(event:DropDownEvent):void
{
super.dropDownController_closeHandler(event);
// Automatically selected all items if no items are selected when closing the dropDown.
if (selectedItems.length == 0 && !selectedAll)
selectedAll = true;
}
override protected function measure():void
{
var labelComp:TextBase = labelDisplay as TextBase;
// If typicalItem is set, then use it for measurement
if (labelComp && typicalItem != null)
{
// Save the labelDisplay's dimensions in case we clear out typicalItem
if (!sizeSetByTypicalItem)
{
labelDisplayExplicitWidth = labelComp.explicitWidth;
labelDisplayExplicitHeight = labelComp.explicitHeight;
sizeSetByTypicalItem = true;
}
labelComp.explicitWidth = NaN;
labelComp.explicitHeight = NaN;
// Swap in the typicalItem into the labelDisplay
updateLabelDisplay(typicalItem);
UIComponentGlobals.layoutManager.validateClient(skin, true);
// Force the labelDisplay to be sized to the measured size
labelComp.width = labelComp.measuredWidth;
labelComp.height = labelComp.measuredHeight;
// Set the labelDisplay back to selectedItem
updateLabelDisplay();
}
else if (labelComp && sizeSetByTypicalItem && typicalItem == null)
{
// Restore the labelDisplay to its original size
labelComp.width = labelDisplayExplicitWidth;
labelComp.height = labelDisplayExplicitHeight;
sizeSetByTypicalItem = false;
}
super.measure();
}
override mx_internal function updateLabelDisplay(displayItem:* = undefined):void
{
if (labelDisplay)
{
if (displayItem == undefined)
{
if (selectedItems != null && selectedItems.length > 1)
displayItem = VectorUtils.vectorToArray(selectedItems, Object);
else
displayItem = selectedItem;
}
if (displayItem != null && displayItem != undefined)
if (displayItem is Array)
{
this.toolTip = selectedItemsToLabel(displayItem, labelField, labelFunction);
labelDisplay.text = (displayItem as Array).length + " selected";
}
else
{
this.toolTip = null;
labelDisplay.text = selectedItemsToLabel(displayItem, labelField, labelFunction);
}
else if (selectedAll)
labelDisplay.text = "All";
else
labelDisplay.text = prompt;
}
}
private function invalidateList():void
{
if (dataGroup == null)
return;
for each (var itemIndex:int in dataGroup.getItemIndicesInView())
{
var renderer:UIComponent = dataGroup.getElementAt(itemIndex) as UIComponent;
if (renderer)
renderer.invalidateDisplayList();
}
}
private function selectedItemsToLabel(item:Object, labelField:String=null, labelFunction:Function=null):String
{
if (labelFunction != null)
return labelFunction(item);
var collection:ICollectionView = null;
if (item is Array)
{
collection = new ArrayCollection(item as Array);
}
else if (item is ICollectionView)
{
collection = ICollectionView(item);
}
else if (item is IList)
{
collection = new ListCollectionView(IList(item));
}
if (collection != null)
{
var itemLabels:Array = [];
for each (var obj:Object in collection)
{
itemLabels.push(obj[labelField]);
}
return itemLabels.join(", ");
}
return LabelUtil.itemToLabel(item, labelField, labelFunction);
}
public function get selectedValues():Array
{
var arr:Array = [];
if(selectedItems != null && selectedItems.length > 0)
{
for each (var obj:Object in selectedItems)
arr.push(obj.value);
}
return arr;
}
public function get selectedLabels():Array
{
var arr:Array = [];
if(selectedItems != null && selectedItems.length > 0)
{
for each (var obj:Object in selectedItems)
arr.push(obj.label);
}
return arr;
}
}
Try to call super() after the addEventListener() in the constructor function
I am using a pair of classes to process and use Sprite Sheets but i have a slight problem, in comparison to the Bitmap class my SpriteSheetClips look very ugly, I scale both, Bitmap and SpriteSheetClip up and down using exactly the same image loaded and they look very different Bitmap looks smooth and nice while my SpriteSheetClips look pixelated with white borders, what is wrong with my classes that is causing this problem?
SpriteSheet (contains the cut bitmapDatas to be used for the clip):
package src {
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;
public class SpriteSheet {
private var frames:Array = new Array();
public function SpriteSheet(spriteSheet:BitmapData, spriteSheetXML:XML)
{
var tileAmount:int = spriteSheetXML.SubTexture.length();
var rect:Rectangle;
var point:Point = new Point(0, 0);
var frame:BitmapData;
for (var a:int = 0; a < tileAmount ; a++)
{
frame = new BitmapData(spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
rect = new Rectangle(spriteSheetXML.SubTexture[a].#x, spriteSheetXML.SubTexture[a].#y, spriteSheetXML.SubTexture[a].#width, spriteSheetXML.SubTexture[a].#height);
frame.copyPixels(spriteSheet, rect, point);
frames.push(frame);
}
}
public function getTile(tileNum:int):BitmapData
{
return frames[tileNum-1];
}
public function get length():int
{
return frames.length;
}
}
}
SpriteSheetClip:
package src {
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
public class SpriteSheetClip extends Sprite{
private var spriteSheet:SpriteSheet;
public var frame:Bitmap;
private var _currentFrame:int = 1;
private var _isPlaying:Boolean = true;
public var isLooping:Boolean = true;
private var frames:Array = new Array();
public function SpriteSheetClip(spriteSheetUsed:SpriteSheet)
{
spriteSheet = spriteSheetUsed;
frame = new Bitmap(spriteSheet.getTile(1), "auto", true);
this.addChild(frame);
for (var a:int = 0; a < totalFrames; a++)
{
frames.push({labelName:"", action:""});
}
this.addEventListener(Event.ENTER_FRAME, onFrameLoop, false, 0, true);
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get totalFrames():int
{
return spriteSheet.length;
}
public function get isPlaying():Boolean
{
return _isPlaying;
}
public function start()
{
_isPlaying = true;
}
public function stop()
{
_isPlaying = false;
}
public function addFrameLabel(frameNum:int, labelName:String)
{
if (frameNum == 0)
{
return;
}
frames[frameNum-1].frameLabel = labelName;
}
public function addConnection(frameLabel:*, connectedFrameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum == 0)
{
return;
}
frames[frameNum-1].action = connectedFrameLabel;
}
private function frameNumber(frameLabel:*):int
{
if (int(frameLabel) <= totalFrames && int(frameLabel) > 0)
{
return int(frameLabel);
}
for (var a:int = 0; a < frames.length; a++)
{
if (frames[a].frameLabel == frameLabel)
{
return (a+1);
}
}
return 0;
}
public function gotoAndStop(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
stop();
}
public function gotoAndPlay(frameLabel:*)
{
var frameNum:int = frameNumber(frameLabel);
if (frameNum > 0 && frameNum <= totalFrames)
{
_currentFrame = frameNum;
}
updateFrame();
start();
}
private function updateFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
}
public function nextFrame()
{
frame.bitmapData = spriteSheet.getTile(currentFrame);
if (frames[currentFrame-1].action != "")
{
this.gotoAndPlay(frames[currentFrame-1].action);
return;
}
_currentFrame++;
if (currentFrame > totalFrames)
{
if (isLooping)
{
_currentFrame = 1;
}
else
{
_currentFrame = totalFrames;
_isPlaying = false;
}
}
}
private function onFrameLoop(e:Event)
{
if (isPlaying)
{
nextFrame();
}
}
}
}
I have a real problem on an ActionScript homework. I have to program a solitaire, and I'm now stuck on a bug that I don't understand.
When I launch my game object, it instanciates a CardDeck object, and fill its array with Card objects. But since my last edit, a "ArgumentError: Error #1063" is thrown every 2 seconds, and i just don't get why. I've looked and tried the few topics related to this Error, but I didn't manage to make it work ...
Here are my classes :
Card.as
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Card extends MovieClip
{
public static const COLOR_RED:int = 1;
public static const COLOR_BLACK:int = 2;
public static const SYMBOL_HEART:int = 1;
public static const SYMBOL_DIAMOND:int = 2;
public static const SYMBOL_SPADE:int = 3;
public static const SYMBOL_CLUB:int = 4;
public var game:Game;
private var t:Timer; // For click/double click fix
private var currentTarget:Card;
public var container:CardStack;
public var color:int;
public var symbol:int;
public var value:int;
public var isVisible:Boolean = false;
public function Card(type:int, value:int, g:Game)
{
game = g;
if (type == SYMBOL_HEART || type == SYMBOL_DIAMOND)
this.color = COLOR_RED;
else
this.color = COLOR_BLACK;
this.symbol = type;
this.value = value;
this.doubleClickEnabled = true;
this.addEventListener(MouseEvent.CLICK, Click);
this.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClick);
}
private function doubleClick(e:MouseEvent):void
{
t.removeEventListener(TimerEvent.TIMER_COMPLETE, onCardClick);
if (t.running)
t.stop();
onCardDoubleClick(e);
}
private function Click(e:MouseEvent):void
{
currentTarget = (Card)(e.currentTarget);
t = new Timer(100,1);
t.addEventListener(TimerEvent.TIMER_COMPLETE, onCardClick);
t.start();
}
public function isSameColor(otherCard:Card):Boolean
{
if (this.color == otherCard.color)
return true;
else
return false;
}
public function setVisible(flipped:Boolean):void
{
if (flipped == true)
{
isVisible = true;
gotoAndStop(value);
}
else {
isVisible = false;
gotoAndStop(14);
}
game.pStage.addChild(this);
}
public function setInvisible():void
{
removeListeners();
game.pStage.removeChild(this);
}
public function removeListeners():void
{
this.removeEventListener(MouseEvent.CLICK, Click);
this.removeEventListener(MouseEvent.DOUBLE_CLICK, doubleClick);
}
private function onCardClick(e:TimerEvent):void
{
var card:Card = currentTarget;
if (this.isVisible == true) {
if (game.flagSelecting == false) {
if (!(card.container == game.deck && game.deck.isHeadCard(card) == false))
game.select.addToSelect(card);
}else{
if (card.container == game.deck)
game.deck.lastPickedCard--;
game.mvOutCard(game.select.tSelect, card.container);
}
}else {
if (((card.container.deckSize()) - 1) == (game.selCard(card, card.container)))
card.setVisible(true);
}
}
private function onCardDoubleClick(e:MouseEvent):void
{
var card:Card = (Card)(e.currentTarget);
// Acestack
if (game.aceStacks.canMoveTo(card) == true)
{
game.moveToAce(card);
}
//K sur place libre
if (card.value == 13) {
var freeStack:CardStack = (game.river.hasFreeStack());
if (freeStack != null){
game.select.addToSelect(card);
game.moveKing(game.select.tSelect, freeStack);
}
}
game.select.reinitSelection();
}
}
CardDeck.as
import Math;
import flash.events.MouseEvent;
import flash.events.Event;
public class CardDeck extends CardStack
{
// THIS IS ABOUT CARDDECK
public var lastPickedCard:int = 0;
public var isEmptyNow:Boolean = false;
// THIS IS ABOUT HANDSTACK
public var handStack:Array = new Array();
public static const X_FIRST_HANDCARD:int = 120;
public static const X_CARD_PADDING:int = 18;
public static const Y_HANDSTACK:int = 62;
public function CardDeck(g:Game)
{
trace("GAME" + g);
var a:Array = new Array();
var nGame:Game = g;
super(a,g);
trace("CONSTRUCTEUR2");
var i:int = 1;
while (i <= 52)
{
if (i < 14)
this.deck.push(new HeartCard(i,g));
else if (i >= 14 && i < 27)
this.deck.push(new DiamondCard(i - 13, g));
else if (i >= 27 && i < 40)
this.deck.push(new SpadeCard(i - 26, g));
else if (i >= 40)
this.deck.push(new ClubCard(i - 39, g));
i++;
}
trace("CONSTRUCTEUR3");
var nDeck:Array;
nDeck = new Array();
var idx:int;
while(this.deck.length > 0){
var r:int = Math.random()*(this.deck.length);
idx = (Math.floor(r));
//deck[idx].container = game.deck;
nDeck.push(deck.splice(idx, 1)[0]);
}
trace("CONSTRUCTEUR4");
this.deck = nDeck;
this.addEventListener(MouseEvent.CLICK, onDeckClick);
this.game.pStage.addChild(this);
this.x = 46;
this.y = 62;
trace("CONSTRUCTEUR5");
}
private function onDeckClick(e:MouseEvent):void
{
trace("LISTENER");
if (isEmptyNow == false)
fillHand();
else
setFilled();
}
public function setEmpty():void
{
this.alpha = .2;
this.isEmptyNow = true;
}
public function setFilled():void
{
this.alpha = 1;
this.isEmptyNow = false;
this.reinitHS();
}
// HANDSTACK
public function showHand():void
{
var i:int = 0;
while (i < (this.handStack.length)) {
trace("SHOW HAND");
handStack[i].setVisible(true);
handStack[i].y = Y_HANDSTACK;
handStack[i].x = X_FIRST_HANDCARD + (i * X_CARD_PADDING);
i++;
}
this.setDepth();
}
public function fillHand():void
{
trace("FILL");
if(lastPickedCard < (deck.length)-3)
this.handStack = this.deck.slice(deck.lastPickedCard, 3);
else {
this.handStack = this.deck.slice(game.deck.lastPickedCard);
this.setEmpty();
}
showHand();
}
public function reinitHS():void {
var i:int = 0;
while (i < (this.handStack.length)) {
handStack[i].setInvisible();
i++;
}
this.handStack = new Array();
}
public function isHeadCard(c:Card):Boolean
{
if (handStack.indexOf(c) == handStack.length -1)
return true;
else
return false;
}
}
CardStack.as
import flash.display.MovieClip;
public class CardStack extends MovieClip
{
public var deck:Array;
public var game:Game;
public function CardStack(newDeck:Array, g:Game)
{
game = g;
this.deck = newDeck;
}
public function isEmpty():Boolean {
if (this.deck.lenght == 0)
return true;
else
return false;
}
public function setDepth():void
{
var i:int = 0;
while (i < (this.deck.length))
{
if (i == 0)
this.deck[i].parent.setChildIndex(this.deck[i], 1);
else
this.deck[i].parent.setChildIndex(this.deck[i], 1 + i);
i++;
}
}
public function deckSize():int {return (this.deck.length);}
}
I call this here :
public function Game(pS:Stage)
{
pStage = pS;
select = new Selection(this);
trace("flag");
deck = new CardDeck(this);
trace("flag2");
aceStacks = new AceRiver(this);
river = new River(deck.deck, this);
}
And I get this exception :
ArgumentError: Error #1063: Argument count mismatch on CardDeck(). Expected 1, got 0
Any help would be really appreciated !
Stab in the dark; assuming that the only line that calls CardDeck() is:
deck = new CardDeck(this);
then I would ask, are you using more than one swf file in your project and loading one in at runtime? If so, try rebuilding all of your swfs that reference the CardDeck class.
I've a flex mobile project and a component (as-Class) inside of it with an BitmapImage, a Button and a Graphic sign.
When a boolean is false the button is disabled, the image gets gray through a ColorMatrixFilter (bitmapImage.filters = [myCMFilter]) and the sign appers, else button is enabled, the image has no filters (bitmapImage.filters = []).
The problem is that the image doesn't switch to grey -> but the sign appears and the button gets disabled.
If call the setting of the filters one frame later (callLater -> a function setting the filters) everything works.
I have extracted the code to a sample project and everything works... without callLater
Anyone an idea what can happpen in my case???
Christian
Code:
package de.xxx.yyy.app.view.componentsV2.widgets
{
import de.assets.header.HeaderBGDarkGray;
import de.assets.miscellaneous.StarGrey;
import de.assets.miscellaneous.StarYellow;
import de.assets.miscellaneous.UnderConstruction;
import de.assets.ImageAssets;
import de.xxx.yyy.app.view.componentsV2.buttons.BasicButton;
import de.xxx.yyy.app.view.pools.UserInterfaceComponentsPool;
import flash.debugger.enterDebugger;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import spark.components.Button;
import spark.components.Group;
import spark.core.SpriteVisualElement;
import spark.primitives.BitmapImage;
public class StadiumWidget extends Group{
private static var STADION_LEVELS:int = 7;
private static var SIDE_SPACING:int = 7;
private static var BUTTON_WIDTH:int = 150;
private static var BUTTON_HEIGHT:int = 33;
////////////////////////////////////////////////////////////////////////////
// USER INTERFACE COMPONENTS
////////////////////////////////////////////////////////////////////////////
private var underConstructionImage:UnderConstruction;
private var currentImage:BitmapImage;
private var footerBackground:HeaderBGDarkGray;
private var developButton:BasicButton;
private var manageButton:BasicButton;
private var displayedlevel:int;
////////////////////////////////////////////////////////////////////////////
// FIELDS
////////////////////////////////////////////////////////////////////////////
private var createdStars:Array = [];
////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////
private var _grayscaleFilter:ColorMatrixFilter;
public function get grayscaleFilter():ColorMatrixFilter
{
if(!_grayscaleFilter)
{
var matrix:Array = [0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0, 0, 0, 1, 0];
_grayscaleFilter = new ColorMatrixFilter(matrix);
}
return _grayscaleFilter;
}
public function set grayscaleFilter(value:ColorMatrixFilter):void
{
_grayscaleFilter = value;
}
////////////////////////////////////////////////////////////////////////////
// GETTER AND SETTER WITH DIRTY FLAG
////////////////////////////////////////////////////////////////////////////
private var levelChanged:Boolean;
private var _level:int;
public function set level(value:int):void
{
_level = value;
levelChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get level():int
{
return _level;
}
//
private var isUnderConstructionChanged:Boolean;
private var _isUnderConstruction:Boolean;
public function set isUnderConstruction(value:Boolean):void
{
_isUnderConstruction = value;
isUnderConstructionChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get isUnderConstruction():Boolean
{
return _isUnderConstruction;
}
////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////
public function Stadium()
{
super();
}
////////////////////////////////////////////////////////////////////////////
// LIFECYCLE STANDARD METHODS
////////////////////////////////////////////////////////////////////////////
var testSprite:UIComponent;
override protected function createChildren():void
{
super.createChildren();
currentImage = new BitmapImage();
currentImage.smooth = true;
currentImage.percentWidth = 100;
currentImage.scaleMode = "letterbox";
addElement(currentImage);
// FOOTER
footerBackground = new HeaderBGDarkGray();
addElement(footerBackground);
developButton = new BasicButton();
developButton.width = BUTTON_WIDTH;
developButton.height = 38;
developButton.x = SIDE_SPACING;
developButton.label = resourceManager.getString("FlexApp", "stadium.developButtonLabel");
developButton.addEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
addElement(developButton);
manageButton = new BasicButton();
manageButton.width = BUTTON_WIDTH;
manageButton.height = 38;
manageButton.label = resourceManager.getString("FlexApp", "stadium.manageButtonLabel");
manageButton.addEventListener(MouseEvent.CLICK, handleManageButtonClicked);
addElement(manageButton);
}
override protected function commitProperties():void
{
super.commitProperties();
if(currentImage && levelChanged)
{
setcurrentImage();
setStars();
levelChanged = false;
}
if(isUnderConstructionChanged)
{
setUnderConstruction();
isUnderConstructionChanged = false;
}
}
override protected function measure():void
{
super.measure();
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var FOOTER_HEIGHT:int = footerBackground.getPreferredBoundsHeight();
var STAR_X_STEP:int = 25;
footerBackground.y = unscaledHeight - FOOTER_HEIGHT;
footerBackground.width = unscaledWidth;
manageButton.x = unscaledWidth - (BUTTON_WIDTH + SIDE_SPACING);
manageButton.y = developButton.y = footerBackground.y + ((FOOTER_HEIGHT - BUTTON_HEIGHT) / 2);
if(currentImage.height > unscaledHeight - footerBackground.height)
{
currentImage.height = unscaledHeight - footerBackground.height;
}
if(underConstructionImage)
{
underConstructionImage.x = (unscaledWidth - underConstructionImage.width) / 2;
}
var starStartX:int = unscaledWidth / 2 - (STADION_LEVELS * STAR_X_STEP) / 2;
var starY:int = createdStars.length > 0 ? unscaledHeight - FOOTER_HEIGHT + (FOOTER_HEIGHT - createdStars[0].height) / 2 : 0;
for(var i:int = 0; i < createdStars.length; i++)
{
createdStars[i].y = starY;
createdStars[i].x = starStartX + i * STAR_X_STEP;
}
}
////////////////////////////////////////////////////////////////////////////
// HELPER METHODS
////////////////////////////////////////////////////////////////////////////
private function setStars():void
{
var pool:UserInterfaceComponentsPool = UserInterfaceComponentsPool.getInstance();
var star:IVisualElement;
while(createdStars.length > 0)
{
star = createdStars.pop() as IVisualElement;
if(containsElement(star))
{
removeElement(star);
}
pool.disposeUserInterfaceComponent(star);
}
// POOL THE STARS!!!
for(var i:int = 1; i <= STADION_LEVELS; i++)
{
if(i <= level)
{
star = pool.getYellowStar();
}
else
{
star = pool.getGreyStar();
}
addElement(star)
createdStars.push(star);
}
}
private function setcurrentImage():void
{
if(level != displayedlevel)
{
currentImage.source = currentImages["LEVEL_" + level + "_NAME"];
displayedlevel = level;
}
setUnderConstruction();
}
private function setUnderConstruction():void
{
developButton.enabled = isUnderConstruction == false;
if(isUnderConstruction)
{
if(!underConstructionImage)
{
underConstructionImage = new UnderConstruction();
underConstructionImage.y = 30;
underConstructionImage.width = 330;
underConstructionImage.height = 330;
addElement(underConstructionImage);
}
callLater(setFilters, [true]);
}
else
{
callLater(setFilters, [false]);
if(underConstructionImage && containsElement(underConstructionImage))
{
removeElement(underConstructionImage);
}
underConstructionImage = null;
}
}
private function setFilters(value:Boolean):void
{
if(value && (!currentImage.filters || currentImage.filters.length == 0))
{
currentImage.filters = [grayscaleFilter];
}
else if(!value && currentImage.filters && currentImage.filters.length > 0)
{
currentImage.filters = [];
}
}
////////////////////////////////////////////////////////////////////////////
// EVENT HANDLER
////////////////////////////////////////////////////////////////////////////
private function handleDevelopButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openlevelPopup", true));
}
private function handleManageButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openManagePopup", true));
}
////////////////////////////////////////////////////////////////////////////
// DISPOSE
////////////////////////////////////////////////////////////////////////////
public function dispose():void
{
developButton.removeEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
manageButton.removeEventListener(MouseEvent.CLICK, handleManageButtonClicked);
}
}
}
I have this MouseEvent function that I have totally no idea why it fired twice. Is there a way I can disable the function in a period of time? I tried disabling the button, but seems like it directly called the function and does not trigger from the button.
Addition info:When I add in more object to the array, the function fired more time
The Class the handles the button
package classes
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import classes.playVideo;
import classes.playList;
import classes.viewType;
public class controlMenu extends MovieClip
{
private var playV:playVideo=new playVideo();
private var list:playList=new playList();
private var viewT:viewType = new viewType();
private static var con:controls = new controls();
private static var _buttonStatus:Boolean;
public function controlMenu()
{
}
//-------------------------------------------------------------
public function loadControlMenu():void
{
this.addEventListener(Event.ADDED_TO_STAGE,add2Stage);
}
private function add2Stage(e:Event):void
{
if (stage.numChildren == 1)
{
con.x=(stage.stageWidth-230)/2;
con.y=stage.stageHeight-(con.height+9);
addChild(con);
playButtonStatus();
con.soundBtn.addEventListener(MouseEvent.MOUSE_OVER, soundOver);
con.soundBtn.addEventListener(MouseEvent.MOUSE_OUT, soundOut);
con.soundBtn.addEventListener(MouseEvent.MOUSE_DOWN, soundDown);
stage.addEventListener(MouseEvent.MOUSE_UP, soundUp);
con.prev.addEventListener(MouseEvent.CLICK,prevClick);
con.next.addEventListener(MouseEvent.CLICK,nextClick);
}
}
private function playClick(e:MouseEvent):void
{
if (e.currentTarget.currentFrameLabel == "play" && playV.currentVideoStatus == "play")
{
e.currentTarget.gotoAndStop("pause");
playV.pauseStatus();
}
else if (e.currentTarget.currentFrameLabel=="pause" && playV.currentVideoStatus == "pause")
{
e.currentTarget.gotoAndStop("play");
playV.playStatus();
}
else if (e.currentTarget.currentFrameLabel == "play"&& playV.currentVideoStatus == "end")
{
playV.newVideo = "video/video" + list.currentIndex + ".flv";
}
}
private function playOver(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("over");
}
private function playOut(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("out");
}
//-------------------------------------------------------------
private function soundOver(e:MouseEvent):void
{
e.currentTarget.gotoAndStop("over");
}
private function soundOut(e:MouseEvent):void
{
if (e.buttonDown == false)
{
e.currentTarget.gotoAndStop("out");
}
}
private function soundDown(e:MouseEvent):void
{
var volumeBound:Rectangle = new Rectangle(-93,35,80,0);
e.currentTarget.startDrag(false, volumeBound);
stage.addEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundUp(e:MouseEvent):void
{
con.soundBtn.stopDrag();
con.soundBtn.gotoAndStop("out");
stage.removeEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundAdjust(e:MouseEvent):void
{
playV.adjustSound = ((con.soundBtn.x+93)*100)/80;
}
public function set adjustSoundBtnPos(a:Number):void
{
var newPos:Number = ((80*a)/100);
con.soundBtn.x = newPos - 93;
}
private function prevClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex > 1)
{
var goBack = list.currentIndex - 1;
list.currentIndex = goBack;
playV.newVideo = "video/video" + goBack + ".flv";
list.currentVideoLink = goBack;
}
}
private function nextClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex < list.vDataLength)
{
var goNext = list.currentIndex + 1;
list.currentIndex = goNext;
playV.newVideo = "video/video" + goNext + ".flv";
list.currentVideoLink = goNext;
}
}
//-------------------------------------------------------------
public function get currentStatus():String
{
return con.playBtn.currentFrameLabel;
}
public function resetPlayStatus():void
{
con.playBtn.gotoAndStop("play");
}
//-------------------------------------------------------------
public function set buttonStatus(s:Boolean):void
{
_buttonStatus = s;
playButtonStatus();
}
public function playButtonStatus():void
{
if (_buttonStatus == true)
{
con.playBtn.buttonMode = true;
con.playBtn.addEventListener(MouseEvent.CLICK, playClick);
con.playBtn.addEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.addEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = true;
con.soundBtn.mouseEnabled = true;
}
else
{
con.playBtn.buttonMode = false;
con.playBtn.removeEventListener(MouseEvent.CLICK, playClick);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = false;
con.soundBtn.mouseEnabled = false;
}
}
}
}
The Class that cause the extra loop on mouseevent function
package classes
{
import flash.media.Video;
import flash.display.MovieClip;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.AsyncErrorEvent;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.media.SoundTransform;
import flash.media.SoundMixer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import classes.Playing;
import classes.progressBar;
import classes.controlMenu;
import classes.viewType;
import classes.downloadVideo;
import classes.playList;
import classes.playVideo;
public class playVideo extends MovieClip
{
private var Play:Playing = new Playing();
private var progressB:progressBar = new progressBar();
private var conM:controlMenu;
private var viewT:viewType=new viewType();
private var downloadV:downloadVideo;
private var list:playList;
private var vBox:MovieClip = new MovieClip();
private var nc:NetConnection;
private static var ns:NetStream;
private const buffer:Number = 2;
private static var videoURL:String;
private static var vid:Video = new Video();
private static var meta:Object = new Object();
private var durationSecs:Number;
private var durationMins:Number;
private var durSecsDisplay:String;
private var durMinsDisplay:String;
private static var videoDuration:String;
private static var t:Timer = new Timer(100);
private static var videoSound:SoundTransform = new SoundTransform();
private var arial:Arial = new Arial();
private static var durationTxt:TextField=new TextField();
private var durationTxtF:TextFormat=new TextFormat();
private var scrubForward:Boolean;
private static var currentStatus;
private static var nsArray:Array= new Array();
private var dummyArray:Array = new Array();
//--------------------------------------------------------------------------
private var videoLoader:URLLoader;
public function playVideo()
{
}
public function set newVideo(v:String):void
{
currentStatus = "play";
videoURL = v;
if (viewT.viewIn == "stream")
{
addVideo();
}
else if (viewT.viewIn=="download")
{
for (var i:uint=0; i<nsArray.length; i++)
{
if (nsArray[i] != null)
{
nsArray[i].close();
}
}
videoProperties();
soundF();
}
conM.resetPlayStatus();
}
public function videoFunction():void
{
vBox.graphics.beginFill(0x000000);
vBox.graphics.drawRect(0,36,668,410);
vBox.graphics.endFill();
addChild(vBox);
// Add the instance of vid to the stage
vid.width = vid.width * 2;
vid.height = vid.height * 1.5;
vid.x = vBox.width / 2 - vid.width / 2;
vid.y = vBox.height / 2 - vid.height / 2 + 36;
vBox.addChild(vid);
if (viewT.viewIn == "stream")
{
videoProperties();
}
soundF();
durationText();
}
public function videoProperties():void
{
nc=new NetConnection();
// Assign variable name for Net Connection
nc.connect(null);
// Assign Var for the NetStream Object using NetConnection
ns = new NetStream(nc);
// Add the buffer time to the video Net Stream
ns.bufferTime = buffer;
// Set client for Meta Data Function
ns.client = {};
ns.client.onMetaData = onMetaData;
// Attach netStream to our new Video Object
if (viewT.viewIn == "stream")
{
vid.attachNetStream(ns);
}
else if (viewT.viewIn == "download")
{
nsArray[list.currentIndex - 1] = ns;
dummyArray.push(ns);
vid.attachNetStream(ns);
}
addVideo();
}
private function addVideo():void
{
// Assign NetStream to start play automatically by default
if (viewT.viewIn == "stream" && videoURL == null)
{
videoURL = "video/video1.flv";
}
ns.play(videoURL);
conM= new controlMenu();
conM.buttonStatus = true;
progressB.progressBarStatus();
// Add Error listener and listeners for all of our buttons
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncErrorHandler);
currentStatus = "play";
t.addEventListener(TimerEvent.TIMER,onTick);
t.start();
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
// Do whatever you want if an error arises
}
private function onMetaData(info:Object):void
{
meta = info;
/*for (meta in info)
{
trace(meta + ":" + info[meta]);
}*/
durationSecs = Math.floor(meta.duration);
durationMins = Math.floor(durationSecs / 60);
durationMins %= 60;
durationSecs %= 60;
if (durationMins < 10)
{
durMinsDisplay = "0" + durationMins;
}
else
{
durMinsDisplay = "" + durationMins;
}
if (durationSecs < 10)
{
durSecsDisplay = "0" + durationSecs;
}
else
{
durSecsDisplay = "" + durationSecs;
}
videoDuration = durMinsDisplay + ":" + durSecsDisplay;
Play.vDuration = videoDuration;
}
//--------------------------------------------------------------------------
public function prepareArray():void
{
list = new playList();
for (var i:uint=0; i<list.vDataLength; i++)
{
nsArray.push(null);
}
}
//--------------------------------------------------------------------------
private function onTick(event:TimerEvent):void
{
if (viewT.viewIn == "stream" || ns.bytesLoaded == ns.bytesTotal)
{
var nsSecs:Number = Math.floor(ns.time);
var nsMins:Number = Math.floor(nsSecs / 60);
nsMins %= 60;
nsSecs %= 60;
var nsSecsDisplay:String = "";
var nsMinsDisplay:String = "";
if (nsMins < 10)
{
nsMinsDisplay = "0" + nsMins;
}
else
{
nsMinsDisplay = "" + nsMins;
}
if (nsSecs < 10)
{
nsSecsDisplay = "0" + nsSecs;
}
else
{
nsSecsDisplay = "" + nsSecs;
}
durationTxt.text = nsMinsDisplay + ":" + nsSecsDisplay;
progressB.progressing = ns.time / meta.duration * 668;
}
else if (viewT.viewIn=="download" && ns.bytesLoaded!=ns.bytesTotal)
{
list.preloadFlv();
}
if (durationTxt.text == videoDuration)
{
currentStatus = "end";
t.stop();
t.removeEventListener(TimerEvent.TIMER,onTick);
ns.pause();
ns.seek(0);
}
}
//--------------------------------------------------------------------------
private function soundF():void
{
var soundAmount:Number = 7;
if (viewT.viewIn == "stream")
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (viewT.viewIn=="download")
{
if (dummyArray.length == 1 && ns != null)
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (dummyArray.length> 1 && ns!=null)
{
ns.soundTransform = videoSound;
}
}
}
public function set adjustSound(s:Number):void
{
videoSound.volume = s / 100;
ns.soundTransform = videoSound;
}
//--------------------------------------------------------------------------
private function durationText():void
{
durationTxtF = new TextFormat();
durationTxtF.size = 12;
durationTxtF.leftMargin = 5;
durationTxtF.font = arial.fontName;
durationTxt.defaultTextFormat = durationTxtF;
durationTxt.selectable = false;
durationTxt.textColor = 0x999999;
durationTxt.width = 50;
durationTxt.height = 22;
durationTxt.x = 476;
durationTxt.y = 477;
durationTxt.text = "00:00";
addChild(durationTxt);
}
//--------------------------------------------------------------------------
public function get Duration():String
{
return videoDuration;
}
public function playStatus():void
{
conM=new controlMenu();
if (conM.currentStatus == "play")
{
ns.resume();
updateProgress();
}
if (currentStatus == "pause")
{
currentStatus = "play";
t.start();
}
}
public function pauseStatus():void
{
ns.pause();
t.stop();
trace("pause");
if (currentStatus == "play")
{
currentStatus = "pause";
}
}
public function get currentVideoStatus():String
{
return currentStatus;
}
public function restartVideo():void
{
ns.resume();
}
//--------------------------------------------------------------------------
public function updateProgress():void
{
ns.seek((progressB.currentProgress / 668) *meta.duration);
}
public function get nsBytesTotal():Number
{
return ns.bytesTotal;
}
public function get nsBytesLoaded():Number
{
return ns.bytesLoaded;
}
public function get getVideoURL():String
{
return videoURL;
}
}
}
I strongly, strongly recommend against doing some sort of flag or timer hack to get around an unexplained behavior - that leads to code bloat and down the line it'll cause you more problems in the long run.
It's much, much, much better to understand why it's calling your function twice. Invest the time in figuring that out (do you have listeners set on multiple display objects? Is this some sort of bubbling issue? Could it be your mouse? Try a clean flash project with just a handler and see if that calls twice, etc), and not only will your code be better and faster but you'll also learn a lot in the process.
You could make a variable so it only runs once. Something like...
var runOnce:Boolean = false;
button.addEventListener(MouseEvent.CLICK, testEvent);
function testEvent(e:Event):void{
if(runOnce == false){
//do stuff here
runOnce = true;
}
It's a bit lazy, but you get the idea.