Copy link to clipboard
Copied
Say I have an MC from the library added to the stage with addChild:
var root = this;
root.addChild(screen1);
Later on, I want to be able to remove the screen1 mc and any event listeners within it, so I have a function:
unloadScreen();
function unloadScreen() {
screen1.removeAllEventListeners();
}
All the above seems to work fine. However, suppose I wanted to be able to use this function for several mcs by passing the ID of the mc into the function as a variable? Something like:
unloadScreen("screen1");
function unloadScreen(theScreen) {
???.removeAllEventListeners();
}
How would I write the "removeAllEventListeners" line within the function? I have tried to figure it out myself, but I have not got anywhere so far. Please note the above is a simplified example; I just want to understand the correct general approach.
No. That's exactly like trying to do "screen1".removeAllEventListeners(). Obviously that won't work because it's a string, not an object.
The code that Julian says above works fine, can't, because that's not how you instantiate new instances from the library. He'd have to do this:
var root = this;
var screen1 = new lib.screen1;
root.addChild(screen1);
However, he wants a generic function to be able to address these dynamically added children. The problem with addChild() is that it adds ins
...Copy link to clipboard
Copied
Try:
function unloadScreen(theScreen) {
theScreen.removeAllEventListeners();
}
and then add the screen name in your function call.
unloadScreen("screen1");
or
unloadScreen("screen2");
Copy link to clipboard
Copied
No. That's exactly like trying to do "screen1".removeAllEventListeners(). Obviously that won't work because it's a string, not an object.
The code that Julian says above works fine, can't, because that's not how you instantiate new instances from the library. He'd have to do this:
var root = this;
var screen1 = new lib.screen1;
root.addChild(screen1);
However, he wants a generic function to be able to address these dynamically added children. The problem with addChild() is that it adds instances anonymously. They don't have associated named reference like timeline objects.
Fortunately, CreateJS has a method getChildByName(). So if you give each symbol a name as it's added...
var root = this;
var screen1 = new lib.screen1;
screen1.name = "banana";
root.addChild(screen1);
Then you can reference them by name...
function unloadScreen(name) {
root.getChildByName(name).removeAllEventListeners();
}