My AS3 application basically does the following (pseudo code from main application class) 3 or 4 times by adding custom objects to stage:
_movieClipClassVariable = new MyCustomSpriteSubclass();
_movieClipClassVariable.addEventListener(MyEvents.READY, function(event:Event):void {
_hideLoading();
mcHolder.addChild(_movieClipClassVariable);
});
_movieClipClassVariable.addEventListener(MouseEvent.CLICK, myClickHandler);
private function coverClickHandler(event:Event):void
{
...
}
What is the right way to allow Garbage Collector to recycle _movieClipClassVariable after it is not necessary? Assign null to it? Remove all listeners? Use weak reference for listeners?
Thanks in advance!
I would say all of the above.
I recommend reading Grant Skinners articles of Resource Management. Also take a look at his slides from his Resource management talk.
There is quite a lot of information out there on this subject, and those two links are the best resources I have found.
In order to get use of garbage collector you should consider:
Not defining handler methods inside the X.addEventListener() call
Remove all event listeners on the object you want to free up from memory
Make the object null
4.(optional) you can force garbage collector calling system.gc();
Related
I want to create a controller based JavaFX GUI consisting of multiple controllers.
The task I can't accomplish is to pass parameters from one Scene to another AND back.
Or in other words:
The MainController loads SubController's fxml, passes an object to SubController, switches the scene. There shall not be two open windows.
After it's work is done, the SubController shall then switch the scene back to the MainController and pass some object back.
This is where I fail.
This question is very similar to this one but still unanswered. Passing Parameters JavaFX FXML
It was also mentioned in the comments:
"This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
– Xlint Xms Sep 18 '17 at 23:15"
I used the first approach in the top answer of that thread.
Does anyone have a clue how to achieve this without external libs?
There are numerous ways to do this.
Here is one solution, which passes a Consumer to another controller. The other controller can invoke the consumer to accept the result once it has completed its work. The sample is based on the example code from an answer to the question that you linked.
public Stage showCustomerDialog(Customer customer) {
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(
new Scene(
(Pane) loader.load()
)
);
Consumer<CustomerInteractionResult> onComplete = result -> {
// update main screen based upon result.
};
CustomerDialogController controller =
loader.<CustomerDialogController>getController();
controller.initData(customer, onComplete);
stage.show();
return stage;
}
...
class CustomerDialogController() {
#FXML private Label customerName;
private Consumer<CustomerInteractionResult> onComplete
void initialize() {}
void initData(Customer customer, Consumer<CustomerInteractionResult> onComplete) {
customerName.setText(customer.getName());
this.onComplete = onComplete;
}
#FXML
void onSomeInteractionLikeCloseDialog(ActionEvent event) {
onComplete.accept(new CustomerInteractionResult(someDataGatheredByDialog));
}
}
Another way to do this is to add a result property to the controller of the dialog screen and interested invokers could listen to or retrieve the result property. A result property is how the in-built JavaFX dialogs work, so you would be essentially imitating some of that functionality.
If you have a lot of this passing back and forth stuff going on, a shared dependency injection model based on something like Gluon Ignite, might assist you.
I've used AfterBurner.fx for dependency injection, which is very slick and powerful as long as you follow the conventions. It's not necessarily an external lib if you just copy the 3 classes into your structure. Although you do need the javax Inject jar, so I guess it is an eternal reference.
Alternately, if you have a central "screen" from which most of your application branches out you could use property binding probably within a singleton pattern. There are some good articles on using singleton in JavaFX, like this one. I did that for a small application that works really great, but defining all of those bindings can get out of hand if there are a lot of properties.
To pass data back, the best approach is probably to fire custom Events, which the parent controller subscribes to with Node::addEventHandler. See How to emit and handle custom events? for context.
In complex cases when the two controllers have no reference to each other, a Event Bus as #jewelsea mentioned is the superior option.
For overall architecture, this Reddit comment provides some good detail: https://www.reddit.com/r/java/comments/7c4vhv/are_there_any_canonical_javafx_design_patterns/dpnsedh/
I just discovered nested functions in AS3 (yeah, late to the party) and am using them in a Flex project. I've always disliked having to use separate functions for essentially modal operations with eventListeners– adds clutter to code and separates operation logic, as well as not being able to easily reference local variables.
The example below for a user selecting a directory seems to work very well and is nice an compact but I am wondering if there are any issues I am not aware of with this approach. Also, with a non-modal operation (e.g. asynchronous like using a Loader), is it possible to use nested functions?
private var rootDirectory:File;
protected function rootBtn_clickHandler(event:MouseEvent):void
{
var tmp:File = File.desktopDirectory;
tmp.browseForDirectory("Set Project Folder");
tmp.addEventListener(Event.SELECT, onUserSelect);
tmp.addEventListener(Event.CANCEL, onUserCancel);
function onUserSelect(event:Event):void
{
tmp.removeEventListener(Event.SELECT, onUserSelect);
tmp.removeEventListener(Event.CANCEL, onUserCancel);
rootDirectory = event.target as File;
}
function onUserCancel(event:Event):void
{
tmp.removeEventListener(Event.SELECT, onUserSelect);
tmp.removeEventListener(Event.CANCEL, onUserCancel);
trace("user canceled");
}
}
There can be some caveats when using anonymous or nested functions.
The first and most important is garbage collection:
In your example, the only thing keeping your tmp object from being garbage collected is the SELECT and CANCEL listeners themselves. Since you are not setting the weak flag to true, this shouldn't be a problem, however, if you we're using the weak flag (tmp.addEventListener(Event.SELECT, onUserSelect,false,0,true)) then there is a decent change the tmp object would get garbage collected before the user SELECTS or CANCELS a file.
Also, it's imperative that you remove every listener that you attached in this way. You are doing that in your onUserCancel method, so it should be fine, but if you were not, then you would have a memory leak on your hands as every time your click handler ran, another instance of tmp would be created but it would never get garbage collected because of the listeners attached to it.
So to summarize, most people stay away from anonymous/nested methods in AS3 (and I generally/usually recommend that to people) because it's easy to create memory leaks or have your closures garbage collected by accident. There also may or not be performance differences, but I have never ran tests in that regard.
first I'd like to thank you for taking the time to read my question.
So, I've made a little flash game(can't really call it a game), anyway at one point I'm checking for if 2 objects hit each other. So to sum it up here's the code
public function loop(e:Event):void
{
y += vx;
if(y > stageRef.stageHeight || y < 0)
removeSelf();
if(hitTestObject(target.hit))
{
removeSelf();
stageRef.dispatchEvent(new GameOverEvent(GameOverEvent.DEAD)); // <--
stageRef.addChild(new SmallImplosion(stageRef, x, y));
}
}
So, when they collide, one object dispatches an event, there is no problem with the code, it works, but I would like to know if it's good to make handle it this way. stageRef is the reference to stage, both classes have it.
And my other class catches that event and it triggers a function, like this:
stageRef.addEventListener(GameOverEvent.DEAD, takeHit, false, 0, true);
The question is, is this a good way to handle it? Thank you in advance!
When implementing the observer pattern, each of the participating objects has a clear role: One is the subject, who is the object where the action is happening, while the other is the observer, who listenes for events on the subjects. In Flash, any object can be the observer, as you pass the handling function to the subscribe-method. Subjects however implement IEventDispatcher and provide the necessary methods to subscribe to the subject. There is also the standard implementation EventDispatcher which already implements the necessary methods (and many types are subtypes of it).
Now back to your question; you are essentially bringing in a third party, the stage where the events are broadcasted on. Instead of having the events that are local to the subject dispatched on the subject itself, you are dispatching them over the global stage, and all observers have to listen to the stage instead of the subject itself.
This is generally not what you should do. Every subject (IEventDispatcher) should only dispatch its own events. Just like you receive a click event from the button that is clicked, you’d receive a GameOverEvent from the object that triggers it.
From the name GameOverEvent, I believe a bit of significance is implied. Since there's plenty to do at the end of a game, I feel it's appropriate for your stage to listen for an event such as this.
However, don't use this technique to handle any smaller systems. For example, if the collision only dealt some damage to the player (I don't know if this even makes sense in the context of your game but roll with me here) then it would be better to have the classes that check for collisions and the classes that handle health to interact directly with one another instead of firing these "Grand Events".
I'm working on a Flash game, and after running my game for a while there is a huge drop in frame rate. There aren't a lot of MovieClips onscreen at once, but MovieClips are being replaced using removeChild and addChild often.
How can one test for problems such as memory leaks? And what are some good AS3 programming standards on this matter?
It seems like you're not preparing your instances of MovieClip for garbage collection. This thread could be extremely helpful to you.
Some of the basic things you want to cover when discarding a MovieClip (or any other Object) properly are:
Remove the object from the DisplayList (if it's a DisplayObject). This is done via what you're doing already, removeChild()
Remove any event listeners that have been applied to the Object. Best thing to do is keep on top of this right from the beginning; by that I mean, when you call addEventListener(), be sure to somewhere in the very near future add a sister removeEventListener() as well.
Remove reference to your Object. This includes, but is not limited to: reference to the Object via being part of an Array/Vector, reference via being stored in a property of another Object, etc.
A suggestion that I can offer is to have in the base class of your objects a method that handles all of this, eg remove() or deconstruct().
Here's an example:
public function deconstruct():void
{
if(parent)
parent.removeChild(this);
removeEventListener(MouseEvent.CLICK, _onClick);
}
And when you extend this class and need other dereferencing features, just build on your deconstruct() method:
override public function deconstruct():void
{
removeEventListener(MouseEvent.MOUSE_OVER, _mouseOver);
var i:int = someArray.indexOf(this);
someArray.splice(i, 1);
super.deconstruct();
}
http://gskinner.com/talks/resource-management/
Let's say that I have a bunch of objects (thumbnails in a matrix for example) and I need to load some data files for all of those over the network (HTTP). So each thumbnail has the thumbnail image itself and an xml file for instance.
There's a number of things that can go wrong from IO errors to bad URLs to badly formatted XML and so on. The question is what is the best / most elegant / most robust way of organizing all of this. What I usually end up doing is having a load manager that tells the
child objects to start loading and then monitors the loading. The child objects have listeners for IO errors and HTTP status events. When all children have loaded everything (with some possible failures) something is done (the thumbnails are shown or whatever).
I was thinking that there has to be a better way of doing this, something that would allow me to maybe use throw clauses when errors occur. Throwing something from the listener isn't going to do much good of course. So what to do. Have a local flag(s) in the child objects and abort if something fails or what?
I am using AS3 but the question should be pretty much the same for other languages, at least for object oriented ones.
Just to be clear I'm not looking for any program code, just general ideas on a design pattern. I also realise that because of the asynchronous load I'm tied in to event handling at least in the child objects.
i use a "queue" package which is able to deal with all sorts of asyncronous operations. the nice thing is you can nest these operations (composite pattern) and create quite complex stuff easily. if events occur you can catch them either at the root as they "bubble up the queue tree) or directly where they originate, depending on the listeners you add.
interface Qable extends IEventDispatcher {
function start()
function stop()
}
interface Q extends Qable {
function add(item:Qable):Q
function remove(item:Qable):Q
...
}
var q1: Q = new Q
q1.add(new Qable(...))
q1.add(new Qable(...))
var q : Q = new Q
q.addEventListener(Event.COMPLETE, onComplete)
q.addEventListener(Event.ERROR, onError)
q.add(new Qable(...))
q.add(new Qable(...)).addEventListener(Event.Error, onItemXError)
q.add(m1)
q.start()