Race condition firing events in AS3
I have some troubles firing and removing events in the right chronicle order. The code below gives the following output:
- save poster into db, and dispatch event
- calling service, dispatch event removed = false
- calling service, dispatch event removed = false
- calling service, dispatch event removed = true
- save poster into db, and dispatch event
- save poster into db, and dispatch event
of course this should be more something like:
- save poster into db, and dispatch event
- calling service, dispatch event removed = true
- save poster into db, and dispatch event
- calling service, dispatch event removed = true
- save poster into db, and dispatch event
- calling service, dispatch event removed = true
Can someone help me with this? I'm running out of ideas on how to tackle this.
thx!
for(var i:int = 0;i< 3;i++){
createPoster();
}
function createPoster(){
Main.db.savePoster开发者_C百科();
Main.db.addEventListener(Config.evt_SAVEPOSTER_READY, callService);
}
function callService(){
Main.db.removeEventListener(Config.evt_SAVEPOSTER_READY, callService);
}
The problem is that you are registering same function callService
for same event Config.evt_SAVEPOSTER_READY
on single EvenDispatcher
objectdb
. So as soon first savePoster dispatches the event after successfully saving the poster, db receives the event and three eventHandlers (in this case callService) are called because callService is registered thrice. So one solution would be dispatching the events from Poster.
for(var i:int = 0;i< 3;i++){
createPoster();
}
function createPoster(){
poster = Main.db.savePoster();
poster.addEventListener(Config.evt_SAVEPOSTER_READY, callService);
}
function callService(e:PosterEvent){
e.target.removeEventListener(Config.evt_SAVEPOSTER_READY, callService);
}
Have you checked what happens when you loop through one item only? Seems to me you are not queuing your routines properly.
You might probably want to add an event listener to your Main.db object only once and remove it when you have gotten all your 'posters' successfully saved.
Is the db call (Main.db.savePoster();
) synchronous - does it return only after the action is completed? Since you are calling addEventListener
after the db call, the event listener (for the first iteration at least) will not be called if the db-call is synchronous.
Is the Main.db
the same instance in all the three iterations? If it is, you don't have to register the same event listener thrice for it - once would be enough. Call addEventListener
before starting the for-loop. Keep a counter for tracking the number of calls to the callService and call removeEventListener
once the counter hits loop count (3, in this case).
精彩评论