Allow custom text representation of data in MXML - apache-flex

I have an actionscript class called Dimension, which allows a client to specify a dimension using a value and a unit such as "CM" or "Inches". I want to use an instance of this class as a property in MXML, so a user can write
<DimensionView value="2cm"/>
How do I make "2cm" an accepted string value for Dimension? I assume I need to write a parser method on my Dimension class, but I can't work out which interface I should be implementing to provide this functionality.
Can anyone help?

One option is to just type the value property as a String, write a getter and a setter for it and do the parsing there:
/**
* docs here
*/
[Bindable(event="valueChanged")]
public function get value():String
{
return _valueInt.toString();
}
/**
* #private
*/
public function set value(aVal:String):void
{
// parse the aVal String to an int (or whatever) here
_valueInt = parsed_aVal;
dispatchEvent(new Event("valueChanged"));
}
On a related note, the framework components implement the feature of allowing for the usage of percentage signs in some sizing properties, when assigned in MXML, by using an undocumented metadata field called PercentProxy. The below example is the width property getter and setter from mx.core.UIComponent:
[Bindable("widthChanged")]
[Inspectable(category="General")]
[PercentProxy("percentWidth")]
override public function get width():Number
{
// --snip snip--
}
override public function set width(value:Number):void
{
// --snip snip--
}

Related

modify groovy trait private field

In my unit tests I usually use reflection to manually inject a mock to the tested class' private field:
static void setFieldValue(Object instance, String fieldName, Object fieldValue, Class instanceClass) {
def field = instanceClass.getDeclaredField(fieldName)
field.accessible = true
field.set(instance, fieldValue)
}
Where instanceClass is the class/superclass, where the class is actually declared. How can I make it work or achieve same result for a private field being declared on a groovy trait?
My IDE helped me - just use the # attribute access notation, where the fieldname is package_dots_replaced_with_underscore_TraitName__fieldName, e.g.
testee.#pl_kamilroman_DeleteEntityBean__messages

why and when to use properties

I am very confused with properties in asp.net.
I just don't understand why we use properties and when I should use them. Could anybody elaborate a little on this.
public class Customer
{
private int m_id = -1;
public int ID
{
set
{
m_id = value;
}
}
private string m_name = string.Empty;
public string Name
{
set
{
m_name = value;
}
}
public void DisplayCustomerData()
{
Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name);
}
}
Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code. Now, lets see how to use properties.
Taken From CSharp-Station
There are a couple of good reasons for it. The first is that you might need to add validation logic in your setter, or actually calculate the value in the getter.
Another reason is something to do with the IL code generated. If you are working on a large project that is spread over multiple assemblies then you can change the code behind your property without the application that uses your assembly having to recompile. This is because the "access point" of the property stays the same while allowing the implementation code behind it to be altered. I first read about this when I was looking into the point of automatic properties as I didnt see the point between those and a normal public variable.
It's easy.
All fields in class MUST be private (or protected). To show fields to another class yyou can use properties or get/set methods. Properties a shorter.
P.S. Don't declare write-only properties. It is worst practices.
Properties are a convenient way to encapsulate your classes' data.
Quoting from MSDN:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods.
Let's consider two common scenarios:
1) You want to expose the Name property without making it changeable from outside the class:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
}
2) You want to perform some checks, or run some code every time the data is accessed or set:
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = (String.IsNullOrEmpty(value)) ? "DefaultName" : value;
}
}
see:
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
The most important reason is for validation purpose in setter and manipulation part can be implemented in get part.
For Ex.
Storing weekdays, which should be from 1-7, if we take normal variable and declare it as public, anyone can assign any value.
But in Properties setter you can control and validate.
The next one you can use it for tracking. That means, you can know how many times set and get functions has been called by clients (statistical purpose, may be not useful frequently).
Finally, you can control read only, write only and read/write for the properties according to your requirements.

Flex: make getter Bindable in an value object

I have an value object in Flex which looks like:
[Bindable]
public class MyVO
{
public var a:ArrayCollection;
public var b:ArrayCollection;
private var timeSort:Sort;
public function ShiftVO(){
timeSort = new Sort();
timeSort.compareFunction = sortDates;
}
public function get times():ArrayCollection{
var ac:ArrayCollection = new ArrayCollection(a.toArray().concat(b.toArray()));
ac.sort = timeSort;
ac.refresh();
return ac;
}
It's about the getter method. I display the data of the getter in a datagrid and whenever I change some values of a or b I want to update the view as well. How do I achieve this? Currently the view doesn't update itself automatically, I have to open up the view again to see the new values.
When you make a property [Bindable], the Flex will read the getter whenever its setter is called (ie, when the property is updated); you haven't declared any setter and hence there is no way for Flex to know that the value of property has been updated.
You must define both a setter and a getter method to use the [Bindable] tag with the property. If you define just a setter method, you create a write-only property that you cannot use as the source of a data-binding expression. If you define just a getter method, you create a read-only property that you can use as the source of a data-binding expression without inserting the [Bindable] metadata tag. This is similar to the way that you can use a variable, defined by using the const keyword, as the source for a data binding expression.
May be you can define an empty setter and call it whenever you update a or b.
public function set times(ac:ArrayCollection):void { }
//somewhere else in the code:
a = someArrayCol;
/**
* this will invoke the setter which will in turn
* invoke the bindable getter and update the values
* */
times = null;
Just noticed that you're using Bindable on the class instead of the property: when you use the Bindable tag this way, it makes
usable as the source of a binding expression all public properties that you defined as variables, and all public properties that are defined by using both a setter and a getter method.
Thus, unless you define a setter, the property is not bindable even if the whole class is declared as bindable.

looping through object property names in actionscript

I have a dynamic class that I have created
public dynamic class SiteZoneFileUploadVO
{
public var destination:String = "sitezone";
public var siteZoneId:uint;
public var fileType:String;
public var fileContents:String;
public function SiteZoneFileUploadVO()
{
}
}
when I try to iterate over this object's property names it only iterates the dynamically added properties.
parameters.dynVar= "value";
for(var name:String in parameters)
{
trace(name);
}
Even though the object has all the properties equal to a value (ive checked this in the debugger) the only property name that will be traced is dynVar.
How can I iterate over all the property names and not just the dynamically added ones?
You can use describeType() to get an XML with all methods and variables of your class and then filter out the properties you want to iterate over (e.g. all variables) and store them in an XMLList.
As the next step you would then iterate over the XMLList and use square bracket notation on your object to access the filtered properties by their names. However, you can only access public properties this way because describeType() won't look at private properties.
If you're running flex:
Looked at a few posts, ObjectUtil.toString was the most promising, then looked at the flex source code for it, it uses another method ObjectUtil.getClassInfo which is exactly what you need. If you just want property names:
ObjectUtil.getClassInfo(myClass).properties
returns an Array of QName objects, each has a localName property which will give you a string for each property name
Just use trace(ObjectUtil.toString(parameters)); That should give you your entire object.

Binding to a read-only getter in AS3

Consider the following code:
[Bindable(event="ReportHeaderVO_effectiveFromDateJulian_updated")]
public function set effectiveFromDateJulian ( value:Number ) : void
{
_effectiveFromDateJulian = value;
dispatchEvent( new FlexEvent("ReportHeaderVO_effectiveFromDateJulian_updated") );
}
public function get effectiveFromDateJulian () : Number
{
return _effectiveFromDateJulian;
}
public function get effectiveFromDate () : Date
{
return DateUtil.convertJDEJulianToDate(_effectiveFromDateJulian);
}
There is a setter and a getter for the effectiveFromDateJulian which is a number representation of the date. I have provided a seperate getter which retrieves the same value, only converted to a proper date. It is a getter only though and relies on the setter for the numeric property to get its data from; so the effectiveFromDate property is effectively read-only.
Data binding works on the effectiveFromDateJulian property; any updates work fine and notify everything properly. But when binding to the effectiveFromDate (getter only) property, I get a warning from the compiler:
warning: unable to bind to property 'effectiveToDate' on class 'com.vo::ReportHeaderVO'
Is there a way to make it possible to bind to this read-only property? I would assume I would have to dispatch an event on the setter that effects the read-only property, but I don't know what that would look like.
This is a simple example, you could imagine a read-only property that depends on several setters to function and when any of those setters are updated the read-only property would need to fire a propertyChanged event as well. Any ideas? Please let me know if I need to clarify anything.
Update:
From the Adobe documentation here:
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_8.html
Using read-only properties as the
source for data binding
You can automatically use a read-only
property defined by a getter method,
which means no setter method, as the
source for a data-binding expression.
Flex performs the data binding once
when the application starts.
Because the data binding from a
read-only property occurs only once at
application start up, you omit the
[Bindable] metadata tag for the
read-only property.
And this makes sense for constant values, but in this case the value does change, it just doesn't get set directly.
Make the readonly getter Bindable and dispatch the corresponding event from the original setter method.
[Bindable(event="ReportHeaderVO_effectiveFromDateJulian_updated")]
public function set effectiveFromDateJulian ( value:Number ) : void
{
_effectiveFromDateJulian = value;
dispatchEvent( new FlexEvent("ReportHeaderVO_effectiveFromDateJulian_updated") );
dispatchEvent( new FlexEvent("ReportHeaderVO_effectiveFromDate_updated") );
}
[Bindable(event="ReportHeaderVO_effectiveFromDate_updated")]
public function get effectiveFromDate (date:Date) : Date
{
return DateUtil.convertJDEJulianToDate(_effectiveFromDateJulian);
}

Resources