Override function of instance of function defined in mxml component script block - apache-flex

I have a protected function defined in a script block of a component defined in mxml like so:
<s:VGroup xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="onCreationComplete()">
<fx:Script>
<![CDATA[
protected function onCreationComplete():void {
}
...
Is it possible to override the function in an instance of the component like so:
<gen:CreateObjectFormSubmit id="formSubmit">
<fx:Script>
<![CDATA[
override protected function onCreationComplete():void {
form=form1;
}
]]>
</fx:Script>

Sure, you can. MXML component is a class , so if you create component B based on component A (B inherits from A), then you can override methods of A in B.

Just be careful with where and how you are declaring your super class. From the syntax provided above, it appears you might be trying to declare a <component> tag in your mxml class, in which if this is the case - the compiler treats this as a separate child object and not an actual extension.
For one, root level tags cannot declare an id (but components can - and this becomes the Class name), and you would most likely need to explicitly declare all your xml namespaces.
In order for it to be a true extension, your first <VGroup> Class would need to be named CreateObjectFormSubmit, this becomes the root tag of your extending class. There is one gotcha though, if you extend from an mxml class you cannot declare any additional children (in mxml notation because of layout rules).
If as you say an instance of your class, then no you wouldn't be able to override it, since the function scope of the <Script> tag would still reside within the root level. This is also sometimes referred to as the 'outerDocument' when declaring <component> tags.
The above wouldn't be any different doing it in regular AS like the following:
class SomethingCool extends UIComponent {
...
public function addButtons():void
{
var btn:Button = new Button();
btn.id = 'formSubmit';
//can't declare an override of Button here
}
}

to override any function, a function which u want to override should be available in parent class of ur current class.
public class A {
public function methodtooverride():void{
trace('in class A');
}
}
public class B extends A {
override public function methodtooverride():void{
trace('in class B');
}
}

Related

Flash builder 4.6 - code behind approach

I'm trying to figure out the right approach for "Code behind" using flash builder for a mobile app:
I'm creating a flex mobile AIR project (Based on the "Tabbed view" template)
setting my UI in design mode
now I want all the logic to be in a separate class that will change the UI look accordingly
Sounds easy, however I can't really get the approach for doing it, any help is appreciated :)
Update:
main app:
<?xml version="1.0" encoding="utf-8"?>
<s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" applicationDPI="160">
<s:ViewNavigator label="a" width="100%" height="100%" firstView="views.aView"/>
<s:ViewNavigator label="b" width="100%" height="100%" firstView="views.bView"/>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:TabbedViewNavigatorApplication>
view A:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="a">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Label id="txt" x="280" y="139" text="Label"/>
</s:View>
So now I want MyClass to change txt textField according to my logic, what is the right approach?
An elegant way would be implementing IMXMLObject. When implementing this interface, the IMXMLObject#initialize method will take the component (named document of type Object) and an optional id (of type String) as arguments and u can easily implement this pattern. The big advantage is, that you use composition over inheritance and when using interfaces, you can use it as some sort of type save mix-in as view behavior:
package net.icodeapp.examples.views
{
import flash.events.MouseEvent;
import mx.core.IMXMLObject;
import mx.events.FlexEvent;
public class ViewBaseModel implements IMXMLObject
{
//-------------------------------------------------------------------------
//
// Properties
//
//-------------------------------------------------------------------------
private var _id:String;
private var _viewBase:ViewBase;
protected function set viewBase(value:ViewBase):void
{
_viewBase = value;
if (!_viewBase)
throw new ArgumentError('View must be instance of ViewBase');
if (!_viewBase.initialized)
_viewBase.addEventListener(FlexEvent.CREATION_COMPLETE, viewBase_creationCompleteHandler, false, 0, true);
else
viewCreationCompleted();
}
//-------------------------------------------------------------------------
//
// Constructor
//
//-------------------------------------------------------------------------
public function ViewBaseModel()
{
}
//-------------------------------------------------------------------------
//
// Methods
//
//-------------------------------------------------------------------------
public function initialized(document:Object, id:String):void
{
viewBase = document as ViewBase;
_id = id;
}
private function viewCreationCompleted():void
{
_viewBase.addEventListener(MouseEvent.CLICK, viewBase_clickHandler);
}
//-------------------------------------------------------------------------
//
// Event Handler
//
//-------------------------------------------------------------------------
private function viewBase_creationCompleteHandler(event:FlexEvent):void
{
viewCreationCompleted();
}
private function viewBase_clickHandler(event:MouseEvent):void
{
// todo: do some action
}
}
}
The model is initialized and references are set by the framework. When taking a peek at the generated ActionScript code you'll see, that IMXMLObject#initialize it called in the constructor after the model is instantiated.
<?xml version="1.0"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:views="net.icodeapp.examples.views.*">
<fx:Declarations>
<views:ViewBaseModel/>
</fx:Declarations>
</s:Group>
The model would receive by events by the view and can call methods on it.
All you do is make an AS file that has the same base class as whatever your MXML object was initially set up as, for example if it's a VGroup make MyBaseClass extends VGroup, then change the VGroup to MyBaseClass.
Example
[Main.mxml]
<main:MainBase
xmlns:main="*"
...>
</main:MainBase>
[MainBase.as]
public class MainBase extends Application
Think of your Code Behind as a base class (or an Abstract Class). In an Abstract Class, it is really common for the actual implementation of methods or the "real objects" behind properties to be left to the extending class(es) to supply.
This is exactly like what you do when you set a base class in Flash to your custom Class, but the actual member objects (buttons, etc.) are provided on the stage of the MovieClip whose library instance is linked to your clip.
For more on code behind, check out my blog post here. If you'd like to check out the code for the template component described there, look here. Though template components are less useful in the Spark world (IMO).

Watching a bindable property

In my flex app I have a public bindable property.
I want it so that every time the value of that property changes, a function gets triggered.
I tried using ChangeWatchers, but it seems those only apply to built-in components like a text box change.
I would like to do that same behavior with a property that changes at runtime.
One option is to use BindingUtils.bindSetter (which incidentally returns a ChangeWatcher):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="this_creationComplete()">
<mx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import mx.binding.utils.ChangeWatcher;
[Bindable]
public var myValue:int = 0;
private function this_creationComplete():void
{
var cw:ChangeWatcher = BindingUtils.bindSetter(myValueChanged, this, "myValue");
}
private function setValue():void
{
myValue = getTimer();
}
private function myValueChanged(o:Object):void
{
trace("myValue: " + myValue.toString());
// You can also use o.toString() -- the new value will be passed into the function
}
]]>
</mx:Script>
<mx:Button label="Click Me" click="setValue()" />
</mx:Application>
Here, myValueChanged gets called whenever the myValue property changes. There are other ways, of course, but I often use this approach with good results. Hope it helps! Post back with questions and I'll keep an eye out.
Look into BindUtils class as back2dos suggests.
And, also, you can set the name of the event that will be triggered when a change is done to a property (default is propertyChange) like this:
[Bindable("change")]
var myProperty : SomeClass;
That is if ChangeWatchers adds listeners for the change event instead of propertyChange event. Which would be kind of weird, but not impossible with all the mishaps of the flex SDKs.
But again, I think BindUtils class should do the trick for you.
Use the class ObjectProxy or its subclass and wrap up the class that has a property you need to watch. In my example, I'm calling a func if someone is changing the property salary giving it a value of more than 55000 in an object Person:
package com.farata
{
import mx.utils.ObjectProxy;
import flash.utils.*;
use namespace flash_proxy;
public dynamic class MyPersonProxy extends ObjectProxy
{
// The object to wrap up
private var person:Person;
public function MyPersonProxy(item:Person){
super(item);
person=item;
}
flash_proxy override function setProperty(name:*, value:*):void {
if ( name == 'salary'&& value>55000) {
// add a new property to this instance of the
// class Person, which can be used in the calculations
// of the total compensation
setProperty("pension", 0.02);
}
super.setProperty(name, value);
}
}
}
well, the easiest way is to listen to PropertyChangeEvent.PROPERTY_CHANGE ... if you declare a property bindable, then mxmlc generates the code to dispatch this event ... if you let the compiler keep the generated ActionScript, then you'll see it ...
other than that, you might want to have a look at BindingUtils ...

setting content area in custom flex component

I am trying to define the content area of a custom component that extends mx:VBox. The component has predefined headers and footers (visual children) and I want to set the area in the middle for adding children to the component. The component will be used like this:
<custom_component>
<mx:button/>
</custom_component>
How would I set this content area?
There's actually a few steps to it.
Your custom component needs to set its DefaultProperty metadata so the children don't collide with the ones within the custom component itself.
Then you need to stow them away in an instance var to add to your content area later, because the properties will be set before the components children are created.
Lastly, if multiple children are specified your DefaultProperty will be handed an Array object (rather than a single UIComponent instance.)
So your custom component would look something like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
<mx:Metadata>
[DefaultProperty("content")]
</mx:Metadata>
<mx:HBox id="headerBox"/>
<mx:VBox id="contentBox"/>
<mx:HBox id="footerBox"/>
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var _contentChildren:Array;
public function set content(c:*) : void {
// Allow 1 or more children to be specified
_contentChildren = (c as Array) || [c];
}
override protected function createChildren() : void {
// Call super so contentBox gets created first
super.createChildren();
for each (var child:UIComponent in _contentChildren) {
contentBox.addChild(child);
}
}
]]>
</mx:Script>
</mx:VBox>
In your custom component, add the DefaultProperty metadata tag:
[DefaultProperty("nameOfDefaultProperty")]
Then you would also define a setter for that property:
public function set nameOfDefaultProperty(value:UIComponent):void
{
if (value != null)
{
// add "value" to the display list here
}
}
Try using a canvas?

Flex AdvancedDataGrid: MXML ItemRenderers are not defaulting to the default style

I know AdvancedDataGrid has a styleFunction callback, but I don't want to change the style; I want the itemRenderer to get the global style that everything else (including normal columns) uses.
My in-line item renderers use the default style, but not the ones I created as separate MXML classes (they extend Canvas).
Any handle I need to jiggle to propagate the style into my item renderers?
Thanks
I don't think you can propagate. Seems like styleFunction is for something completly different. But you can access any CSS property
var styleDecl:CSSStyleDeclaration = StyleManager.getStyleDeclaration("YourTagOrClassName");
and then:
styleDecl.getStyle(property);
If you want to get style declaration directly from the AdvancedDataGrid you have to get renderers listData:
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
implements="mx.controls.listClasses.IDropInListItemRenderer">
<mx:Script>
import mx.controls.dataGridClasses.DataGridListData;
import mx.controls.listClasses.BaseListData;
[Bindable("dataChange")] private var _listData : BaseListData;
public function get listData():BaseListData
{
return _listData;
}
public function set listData( value : BaseListData ) : void
{
_listData = value;
}
override public function set data(value:Object):void
{
super.data = value;
if (this.listData)
((this.listData as DataGridListData).owner as AdvancedDataGrid).getStyle(...);
}
</mx:Script>
</mx:Canvas>
My Bad
It was picking up the style from the ADG; that component's style was not defaulted to the global style.

Access to elements defined in MXML from External AS

I have a MXML with a form, and inside it, two TextInputs. I hate having any piece of code inside the MXML file (I come from a JavaScript formation) so I use a
mx:Script source="external.as"
tag to include any code used in any MXML file. The problem is that if I have this code on the external.as file:
private function populateFromForm():void{
var vo:ValidObject= new ValidObject();
vo.market = marketInput.text;
vo.segment = segmentInput.text;
vo.priceLow = priceLowInput.text;
vo.priceHigh = priceHighInput.text;
}
Where marketInput, segmentInput, priceLowInput and priceHighInput are TextInputs defined in the MXML file. When I try to complile I get a 1120: Access to undefined property XXXXX
I have tried adding this lines prior to the function:
public var marketInput:TextInput;
public var segmentInput:TextInput;
public var priceLowInput:TextInput;
public var priceHighInput:TextInput;
But instead I get a 1151:A conflict exists with definition XXXX in namespace internal which makes perfect sense.
Is there a way to do this without having to pass all the input references to the function as parameters of it?
You need to create a reference to an instance of the TextInputs' parent container, and then use that reference to accsess the TextInputs and their properties. I think we need some clarification on your file structure. How are you creating the instance of the parent container? I'm thinking this is what you need to do:
MyForm.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:TextInput id="marketInput" />
<mx:TextInput id="segmentInput" />
<mx:TextInput id="priceLowInput" />
<mx:TextInput id="priceHighInput" />
</mx:VBox>
SaveVOContainer.as:
package
{
public class SaveVoContainer extends Container
{
private var myForm:MyForm = new MyForm();
public function SaveVOContainer
{
this.addChild(myForm);
}
private function populateFromForm():void{
var vo:ValidObject= new ValidObject();
vo.market = myForm.marketInput.text;
vo.segment = myForm.segmentInput.text;
vo.priceLow = myForm.priceLowInput.text;
vo.priceHigh = myForm.priceHighInput.text;
}
}
}
Doing a "code-behind" is painful in Flex. There is no concept of partial classes or the flexibility of prototypal inheritance as in Javascript. Google for "code-behind in flex" for many resources.
I think it's better you get used to the idea of embedding code in mxml. Use script tags avoiding inline code as much as possible. If you have to write a lot of code within MXML, perhaps you may want to re-factor the code into multiple custom components. Bonus points if they are reusable.
The canonical way to do code-behind in Flex is via inheritance. Here's a good explanation from the docs: http://learn.adobe.com/wiki/display/Flex/Code+Behind. In a nutshell:
Declare an ActionScript class to use as your base class.
Set the base class as the root container in your MXML file.
For any controls declared in your MXML file, you have to redeclare them as public members of the base class using the exact same name (exactly as you are doing above for your script block with source tag, only it works :-)
So, your ActionScript file:
package mypackage
{
import mx.controls.TextInput;
public class myClass extends WindowedApplication
{
public var marketInput:TextInput;
private function populateFromForm():void{
/* As above */
}
}
}
And the corresponding MXML file:
<?xml version="1.0" encoding="utf-8"?>
<custom:myClass xmlns:custom="mypackage.*"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<mx:TextInput id="marketInput"/>
</custom:myClass>
Et cetera for your other TextInput controls. And now your populateFromForm function should work.
It is kind of heinous to have to redeclare the same entities twice, but it's not quite the bag of hurt the earlier respondent made it out to be (although it's possible this changed in Flex 4 to make it less painful than it was).
import this in .AS:
import mx.core.Application;
in the .AS use this:
mx.core.Application.application.component.property = value;
mx.core.Application.application.myText.text = 'test';
do you have a script tag in your mxml file that points to your ActionScript file?
<mx:Script source='includes/foo.as' />

Resources