How much information should one pass through events? - actionscript-3

Say, I have a datagrid with checkboxes, and each time a checkbox is marked I store the object in the data property of flex ResultEvent
public class MyItemRenderer extends ItemRenderer{
public static var CLICK:String = "CheckBoxClick";
protected function itemRendererClickListener(data:Object):void{
dispatchEvent(new ResultEvent(MyItemRenderer.CLICK, data))
}
}
I handle the result here.
protected function checkbox_clicked(event:ResultEvent):void{
//Here I do everything I want with the data.
Alert.show(event.result.toString());
}
This is what I've been using for months, but I never wondererd if this was a bad practice.
Or let alone bad practice, what is the optimal way to do this?

it's not really 'bad'. But it does create an additional reference to an object that can potentially keep that object in memory longer (or indefinitely if not managed well).
Generally speaking, you should only store data related to the event itself in the event instance. You can use the event.target and event.currentTarget properties to reference back to the object that dispatched the event and get data that way.
In your case, your event is a check box state change. The event itself (being checked) doesn't need any data associated with it besides the item being checked (which you can get with 'target' or 'currentTarget'). So it would be more appropriate in my opinion to do the following:
Alert.show(MyItemRenderer(event.currentTarget).data.toString());
This keeps your events more reusable

Best practice for Events with data is to use a custom event (see http://cookbooks.adobe.com/post_AS3__Creating_and_dispatching_Custom_Events-17609.html) for explanation
btw, another 'best practice' is to avoid the generic Object class in your code - instead, create a value object class

Related

Custom Event Listener- un able to understand reasoning behind constance variable

I was following a tutorial online to create a custom event listener. i have some of an understanding of how it works, but its still somewhat confusing. i know that public static Constance DEAD:String = "dead" is a variable (a string) that equals the value "dead", however i do not understand why you need to create this variable just so (type:String) can turn into (DEAD:String). for instance, if you get the value "dead" is that just a default value since it could literally be anything? thanks.
package
{
import flash.events.Event;
public class AvatarEvent extends Event
{
public static const DEAD:String = "dead";
public function AvatarEvent( type:String )
{
super( type );
}
}
}
The value of the string is used by the EventDispatcher to identify the listeners to be notified when the event is dispatched.
The constant is for you, developer, to help you to write clean code, and avoid to create some silly bugs. When writing
dispatchEvent(new AvatarEvent(AvatarEvent.DEAD))
you avoid the typo that could occur in
dispatchEvent(new AvatarEvent(“dead”))
and allow the compiler to check the parameter you give to your event's constructor.
To go further, you could use Robert Penner's AS3Signals, which was written as a replacement for AS3 custom events. It solves many of the drawbacks of the custom events. By example, it does not use strings to identify events, so you can't have any conflict created by two events with the same type value. And it avoids creating a new object each time you want to dispatch a new event, so it is better for performances.

Compatability when passing object to class

Ok, so this might be me being pendantic but I need to know the best way to do something:
(This is psudocode, not actual code. Actual code is huge)
I basically have in my package a class that goes like this:
internal class charsys extends DisplayObject {
Bunch of Variables
a few functions
}
I another class which I intend to add to the timeline I want to create a function like this:
public class charlist {
var list:Array = new Array();
var clock:Timer = new Timer(6000);
var temp:charsys;
function addObj(MC:DisplayObject, otherprops:int) {
temp=MC;
temp.props = otherprops;
list.push(temp)
}
function moveabout(e: event) {
stuff to move the items in list
}
function charlist() {
stuff to initialize the timers and handle them.
}
}
So the question is, is my method of populating this array a valid method of doing it, is there an easier way, can they inherit like this and do I even need to pass the objects like I am?
(Still writing the package, don't know if it works at all)
Yes, you can pass an object into a function, but you should be careful of what you are planning to do with that object inside that function. Say, if you are planning to pass only charsys objects, you write the function header as such:
function addObj(MC:charsys, otherprops:int) {
Note, the type is directly put into the function header. This way Flash compiler will be able to do many things.
First, it will query the function body for whether it refers to valid properties of a passed instance. Say, your charsys object does not have a props property, but has a prop property, this typing error will be immediately caught and reported. Also if that props is, for example, an int, and you are trying to assign a String value to it, you will again be notified.
Second, wherever you use that function, Flash compiler will statically check if an instance of correct type charsys is passed into the function, so if there is no charsys or its subclass, a compilation error is thrown.
And third, this helps YOU to learn how to provide correct types for functions, and not rely on dynamic classes like MovieClip, which can have a property of nearly any name assigned to anything, and this property's existence is not checked at compile time, possibly introducing nasty bugs with NaNs appearing from nowhere, or some elements not being displayed, etc.
About common usage of such methods - they can indeed be used to create/manage a group of similar objects of one class, to the extent of altering every possible property of them based on their corresponding values. While default values for properties are occasionally needed, these functions can be used to slightly (or not so slightly) alter them based on extra information. For example, I have a function that generates a ready-to-place TextField object, complete with formatting and altered default settings (multiline=true etc), which is then aligned and placed as I need it to be. You cannot alter default values in the TextField class, so you can use such a function to tailor a new text field object to your needs.
Hope this helps.
This would work, I think I would assign values to the properties of the charsys object before passing it into the add method though, rather than passing the properties and having a different class do the property assignment. If you have some common properties they could either have defaults in charsys class definition or you could set literals in the addObj method.

Sharing data between model & view of an app

I'm currently trying to find a "definitive" solution (meaning : finding a solution that seems efficient a complying with OOP precepts) to a recurring problem I've been experiencing for some time : the problem of shared data in different parts of my code.
Take note that I'm not using any MVC framework anywhere here. I'm just refering to my data class as a Model and to the display class as a View (because its the proper names and have nothing to do with the MVC pattern, people made views & models way before the MVC pattern was "created").
Here's my problem :
Whenever I make an application that uses some quite expanded data (for example a game), I try to separate logic (movements, collisions, etc...) and display in two classes. But then, I stumble upon the problem : how to "bind" the data stored in my logic class with the corresponding display objects in my view class, without duplicating data, references, or other things between the different classes ?
Lets take a basic example :
I have a MyLogicClass, holding a Vector of "EntityData" objects (each with position, sizes, various states, everything to handle the logic of my items)
And I have a MyViewClass, creating and displaying Sprites for each EntityData that are in the MyLogicClass, and make them move after them being updated in the game loop.
The first thing that would come to my mind would be to store inside each data element its corresponding view, thus allowing me to loop throught my Vector to update the items logic then update the views accordingly. But that forces me to hold a MyLogicClass reference inside the MyViewClass, to be sure that I can target the entities data, forcing me to couple the two classes (things that I would prefer not to do).
On the other hand, there's the solution of each Entity having an ID, both in my data model (MyLogicClass's EntityData objects having an ID parameter) and in my View class (Sprites holding a reference to its original entity data ID). But when I want to target a specific entity that forces me to loop for it in my data model, then loop for it again to find the related Sprite in my View. This solution allows me to have loose coupling between my data and my view, but looping through hundreds of elements twice every frame (can happen !) really sounds not performance optimized for me.
I may be giving the whole problem a lot more importance that it should deserve, but I've been stumbling upon that more than one time, and I'd love to have some other views than mine about that.
Do you guys have any advice / solution for such an issue ?
Are there some other data formats / hierarchy that I may not be aware of for such case ?
What I've done is 'link' them together using events and event listeners. I have my "model parts" throw specific events that the "display parts" catch and render/update.
I've found this does let me structure some of my tests by writing testing code that would listener for certain events and error checks it that way. My code is still separated and testable on it's own: I can test my "model" by triggering and making sure the right events with the right values are being thrown. Like-wise, I can write some testing code to throw preset events that can be caught by the "display" to see if it has any issues.
Then once it is all working, I just reuse those same event listeners and link to 'each other'.
Later my "controller" (user input) would manipulate the "model" parts, which would cause events to be thrown to the "display" thus be rendered/updated.
I don't know if this is "correct" or not in terms of following the mvc pattern nor do I really have any formal knowledge on these sorts of things. I'd be interested in someone else's more knowledgeable opinion as well.
I think maybe you have over thought the problem. I do this sometimes.
Your view class has to have some type of link to the model obviously and an event is a great way to do it. Something bare bones here to give you an idea.
// Model class
package
{
class MyModel extends EventDispatcher
{
// you can make them public but that would
// be against some oop practices. so private it is
private var m_position:Vector2D;
MyModel(){}
// one way of doing getters/getters
// example: theModel.SetPosition(something);
public function GetPosition():Vector2D { return m_position; }
public function SetPosition(value:Vector2D):void
{
m_position = value;
ModelChanged();
}
// the other way
// sample: theModel.position = something;
public function get position():Vector2D {return m_position; }
public function set position(value:Vector2D):void
{
m_position = value;
ModelChanged();
}
private function ModelChanged():void
{
dispatchEvent(new Event(Event.CHANGE));
}
}
}
// now for our view.
package
{
class MyView extends Sprite // or whatever
{
private var model:MyModel;
MyView(model:MyModel)
{
this.model = model;
model.addEventListener(Event.CHANGE, handleModelChanged);
// fire off an event to set the initial position.
handleModelChanged(NULL);
}
private function handleModelChanged(evt:Event):void
{
x = model.position.x;
y = model.position.y;
// etc etc etc.
}
}
}
Anyhow you don't need the setters if your going to have the logic in the model file also obviously if nothing outside of the model needs to change it no reason for setters. But you do need the getters.
This decouples the model from the view and you can write any view any way you want and all you have to provide is a handler for when the model has changed. Just expose whatever data your views will need with getters.
You now only have to loop through the models and if one changes it will fire off an event and the views that are listening in will update.
hope I didn't miss anything and that explains what you were wanting.
Edit: I forgot to add, you don't have to have "ModelChanged()" all over the place if your using something like an update function. Just update and when your finished fire off the event.

Access of undefined property data flex

I'm learning flex/flash and I'm lost on this one. I have used the "data" in a bunch of views and it works fine. For some reason it isn't working here.
I set a field to a string here:
function LoginLoaded (e:Event):void {
trace(e.target.data);
var ServerReturn:String;
ServerReturn = new String(e.target.data);
data.UserCommonReturnData = ServerReturn;
navigator.pushView(CommonPlaces, data);
}
and here in the common places view I try to load it back:
var CommonPlacesData:String = new String();
var CurrentSelect:String = new String();
CommonPlacesData = new String(data.UserCommonReturnData);
This gives the error "Access of undefined property data" I don't get it because calling on something like data.PickUpTime (also a string) works fine in other views.
The data begins in the first view like this:
[Bindable] public var User:ObjectProxy = new ObjectProxy();
User.ID = "2314084";
navigator.pushView(TaxiNowOrLaterView, User);
then in later views I call on it like this: (works fine)
var PickUpString:String = new String(data.ID);
Any help would be great!! Thanks!!!
There are few things about your code. First, you really should make it a habit to name the identifiers as appropriate to the language. Identifiers that start with the capital letter and subsequently use minuscule letters for the rest of the logical part of the word (system alternatively known as PascalCase) is employed to only name classes. The rest of identifiers should use camelCase (similar to PascalCase, but the first letter isn't capitalized)**. This greatly reduces the effort at understanding your code. A seasoned AS3 programmer would interpret your code as follows:
// Static constant (!) ID of the class User is assigned (?) a value of "2314084"
User.ID = "2314084";
// invoke a method pushView of a local variable navigator with arguments
// of which first is the class TaxiNowOrLater, the second is the class User
navigator.pushView(TaxiNowOrLaterView, User);
while, perhaps, you didn't mean it.
new String();
In the context of AS3 makes no sense at all. Strings are never references, are immutable and have literal syntax the majority of programmers agreed upon. The code above is identical to "". In the similar way, new String(anotherString) has exact same effect as anotherString.
Your question: event.target may be many different things, some of them may have property called "data" and some may not. The general approach to this problem is that you need to cast the value of event.currentTarget or event.target to the type you expect to dispatch the event. Suppose you are expecting an event from an instance of a Button class, then:
private function clickHandler(event:MouseEvent):void {
if (Button(event.currentTarget).enabled) // do things
}
This will not protect you from an error, if the same event was dispatched by an object, which is not a button, but will make the error reporting more conscious, because it would tell you what class was it trying to cast to what other class, when it failed.
If your program logic requires that the handler be aware of events it shouldn't handle (why?) you could then write it like this:
private function clickHandler(event:MouseEvent):void {
var button:Button = event.currentTarget as Button;
if (button && button.enabled) // do things
}
event.target vs event.currentTarget - very-very rarely you would need the event.target, most of the time you need the currentTarget. I'm not saying it is wrong, but, it looks like it might be the problem. target is the object that was the first cause of the event. Events may bubble, which means they may travel the display list hierarchy up and down, first from the parent to child, then in reverse direction. In the example below, suppose there was a label on the button, which was clicked once the event was generated - in such case, even if you added a listener to the button, event.target would be the button label, not the button. currentTarget is, on the contrary, the immediate object which dispatched the event into the handler.
Few more things: ObjectProxy is an idiotic class, you probably shouldn't use at any event. It serves no purpose and, perhaps, buggy, but very few cared to discover its bugs so far. In a nutshell, what it does is as follows: it creates an object, which "watches" dynamic creation, assignment and removal of its properties and dispatches events when these events happen. This behavior is prone to a lot of errors and implicit bugs. For example, is foo.bar = "baz"; foo.bar = "baz"; a reassignment of the same property or not? Is foo.bar.baz = "fizzbuzz"; a modification of foo.bar? What if property name is not a sting? And so on.
Why you shouldn't use it: there is always a better way to treat your data. A more transparent, easier to debug, more efficient. This class is a prototype, which had never really worked. Besides having the behavior described above, it is huge in terms of lines of code that were used to write it. Debugging the errors that happen inside of it requires a lot of time and patience, which are certainly not worth it.
If you need an object to represent a user, define a class, with properties you expect the user to have and just use that class - this will make debugging and understanding your code much easier.
[Bindable] metadata is evil. I can't tell you you should avoid it, because it is used too often, but, I will. You should avoid it as much as possible. I didn't yet encounter an instance of when the use of this meta would be justified. Much in the similar spirit as ObjectProxy it is a prototype, something designed for lazy programmers w/o much consideration for either performance or corner cases. This is, again, a source of a lot of implicit bugs, typically difficult to spot due to the code generated around this meta "swallowing" the errors. The alternative to this meta is plain addEventListener(...) code with custom events.
Unfortunately, a lot of tutorial will use this kind of code to have you quickly started with the language + framework...
** there are some exceptions to this rule: constants are all upper-case and namespace names use underscores to separate the logical part of the word, but never use uppercase letters.

How to add one listener for all events?

EventDispatcher.addEventListener() expects first parameter for event type (parameter of String type).
But the current object can generate multiple types of events.
Is it possible to handle all of them in one handler? May be I can pass null for type parameter or something?
You should try to make way around and extend dispatchEvent function :
public override function dispatchEvent(evt:Event):Boolean {
trace(evt.type);
return super.dispatchEvent(evt);
}
You can put Your code here to handle all events dispatched in this object .
Yes, this is possible.
If you use getQualifiedClassName of the Event class, you could get the types using describeType. Then you know all types that could be added, assuming you are using a custom event with public static types as strings in same event class. Then you could loop through all types, and add listeners with all those types to the dispatcher.
This idea is included in the templelibrary (EventUtils.addAll), which I suggest to use.
See documentation: http://templelibrary.googlecode.com/svn/trunk/doc/temple/utils/types/EventUtils.html