Reputation: 820
I am trying to coding a part of a program which is creating different listener for the same object by using a for, but the problem is that the result for all of them is the same, In the following you can find my code:
for( var i:int=0;i<10;i++){
var obj = new MyClass();
obj.y = i*30;
obj.addEventListener(MouseEvent.MOUSE_UP, function(e:MouseEvent){
value = i.toString();
trace(value);
});
myOtherMovieClip.addChild(obj);
}
My goal of writing the code above is, by clicking on the first obj, the program writes 0 in output, by clicking on second one, writes 1 and so on, but this code give me 10 for all the objects.
I should add that no matter there is an obj or not in myOtherMovieClip area, by clicking in that area, I got the same value.
Any idea will be appreciated, Thanks
Upvotes: 0
Views: 102
Reputation: 6402
There is a simple fix. Id your object.
Of course id will have to be a property on MyClass
for( var i:int=0;i<10;i++){
var obj = new MyClass();
obj.y = i*30;
obj.id = 'someMC_' + i
obj.addEventListener(MouseEvent.MOUSE_UP, function(e:MouseEvent){
var aVar:Array = e.target.id.split('_')
trace(aVar[1]);
});
myOtherMovieClip.addChild(obj);
}
Upvotes: 0
Reputation: 3548
In order to directly solve your problem you could do that :
obj.addEventListener(MouseEvent.MOUSE_UP, function():Function{
var value : String = i.toString();
var listener : Function = function(e:MouseEvent):void{
trace(value);
}
return listener;
}());
Upvotes: 1
Reputation: 16934
The best way to achieve this is to set a value property to the MyClass
object.
Or, techinically, if the y
property is constant you could do:
var value:String = (e.target.y / 30).toString();
Upvotes: 1