How to access a Class in the default package from a sub package Class in Flash AS3.0 - actionscript-3

I got error message when trying to access a class in the default package from the class in its sub package. Can any one help me to sort this out.
FYI, my package structure is A -> B. I meant folder 'A' as default package and 'B' as sub package.
Thanks in advance.

Just create a object of Class A, and call class instance method, from its object.
var classAObj:A = new A();
classObj.MethodA();

I think what you're looking for is for class B to extend class A. That would look something like this in your code:
package main
{
class B extends A
{
// Code here...
}
}
Having code inside packages does not in general affect functionality, it's more an organizational tool. (Except for the internal keyword.)

how about private, protected and public ? I could not see any explanation in the other answers so here it is.
class A
{
private var _password:String;
public var username:String;
protected var serverURL:String;
public function login():void
{
// some code
callServerForLogin();
}
protected function callServerForLogin():void
{
// some code
}
}
class B extends A
{
public function B()
{
var parentPassword = super._password;
// FAILS because private and accessible only inside class A
var parentUsername = super.username
// all ok in here, public property
var parentServerURL = super.serverURL;
// all ok, because it is protected
// also we can call super.login(); or super.callServerForLogin();
}
// IMPORTANT we are also allowed to override public and protected functions
override public function login():void
{
super.login();
// we call the parent function to prevent loosing functionality;
Alert.show("Login called from class B");
}
override protected function callServerForLogin():void
{
super.callServerForLogin();
// keep also parent logic
Alert.show("calling protected method from B");
}
}
// ---- Now considering you declare an object of type B you can do the following
var bObj:B = new B();
// access public properties and call public functions from both B and A
bObj.username = "superhero";
bObj.login();
// will get compile error for next lines
bObj.serverURL = "host.port";
bObj.callServerForLogin();

Related

Flex actionscript, get data from AsyncToken call

I have Flex/Java project with blazeDS. Now I have an actionscript file that call a method of another actionscript that call the remoteObject (java class who make a simple select on db)
Here's the code:
Home.as
..
private var _dm:DataManager = new DataManager;
public function getPerson():void { // this is connect to a button in .mxml
_dm.getPerson();
}
..
DataManager.as
public class DataManager {
private var _service:RemoteObject;
private var _url:URLRequest;
private var loCs:ChannelSet = new ChannelSet();
public function DataManager () {
_service = new RemoteObject("PeopleDAO");
loCs.addChannel(new AMFChannel("canale", "http://localhost:8080/FlexTRYOUT/messagebroker/amf"));
_service.channelSet = loCs;
}
private function onFault(event:FaultEvent,token:Object):void {
var _fail:String = "fault";
}
private function onResult(event:ResultEvent,token:Object):void {
per = event.result as People; // is a bean class
Alert.show(per.nome);
}
public function getPerson():void {
var token:AsyncToken = _service.getPersona();
token.addResponder(new AsyncResponder(onResult,onFault));
}
}
The call works fine, it calls java method names getPerson() of the DataManger.java class. It return simply one object with name and surname (it's just a hello world to understand this damned AsyncCall). The problem is that I don't know how send this result to Home.as with a classic (java) return type. I have the result in onResult method and I don't know how to get it.
I try to follow Brian instructions and I just waste my time. Maybe because I'm not a flex actionscript programmer but I added the code Brian posted and:
public function getPerson():void { // this is connect to a button in .mxml
_dm.addEventListener(DATA_RECEIVED, onPersonFound); * compile error 1
_dm.getPerson();
}
error is DATA_RECEIVED is undefined
than in DataManager:
public class DataManager {
public static const DATA_RECEIVED:String = "DATA_RECEIVED";
...
private function onResult(event:ResultEvent,token:Object):void {
per = event.result as People; // is a bean class
dispatchEvent(new DataReceivedEvent(DATA_RECEIVED, per)); * compile error 2
}
}
error 2 is call of possible undefined method dispatchEvent
Where is the mistake? Please guys write the complete code because I'm on flex - actionscript - blazeds from two days and I have a few time to try solution. Thanks
OK, Sorry for all this post, I just create new one (but more elaborated and clear) with the same question. Step by Step I'm studing this language and I manage to implement the Brian code but DataManager.as class must extend EventDispatcher, if I don't extend this I have the compile error I posted. At moment I mangage to obtain the resultEvent data in the method defined in the addEventListener call (onPeopleFound in this case). Thanks a lot Brian I think I surely need your help again in future (at least until acceptance of the project). Bye
You can adjust method getPerson to have two parameters referencing the callback functions.
public function getPerson(onResultCallback:Function, onFaultCallback:Function):void {
var token:AsyncToken = _service.getPersona();
token.addResponder(new AsyncResponder(onResultCallback,onFaultCallback));
}
This way you can receive data in an instance of the class you need.
One option is to dispatch an event when you get the data back from the Java call:
Home.as
...
public function getPerson():void { // this is connect to a button in .mxml
_dm.addEventListener(DATA_RECEIVED, onPersonFound);
_dm.getPerson();
}
private function onPersonFound(dataEvent:DataReceivedEvent):void {
var person:People = dataEvent.people;
//Do important processing...
}
...
In DataManager.as
public class DataManager {
public static const DATA_RECEIVED:String = "DATA_RECEIVED";
...
private function onResult(event:ResultEvent,token:Object):void {
per = event.result as People; // is a bean class
dispatchEvent(new DataReceivedEvent(DATA_RECEIVED, per));
}
}
And DataReceivedEvent.as will look like the answer to How to dispatch an event with added data - AS3
public class DataReceivedEvent extends Event
{
public static const DATA_RECEIVED:String = "DATA_RECEIVED";
// this is the object you want to pass through your event.
public var result:Object;
public function DataReceivedEvent(type:String, result:Object, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.result = result;
}
// always create a clone() method for events in case you want to redispatch them.
public override function clone():Event
{
return new DataReceivedEvent(type, result, bubbles, cancelable);
}
}

AS3 undefined function #1006

I have a parent class called 'main.as'. I am trying to get the child class to call main's function. They both reside in the same folder.
// main.as //
package {
public class main extends MovieClip {
public function main() {
var child:child_mc = new child_mc(this);
}
public function callFunction():void {
trace("Done it");
}
}
}
.
// child.as //
package {
import main;
public class child extends MovieClip {
private var main:MovieClip = new MovieClip();
public function child(main:MovieClip):void {
this.main = main;
main.callFunction();
}
}
}
This is the error I've been getting:
TypeError: Error #1006: callFunction is not a function.
so I tried doing a trace like this
trace(main.callFunction);
and it says undefined. Can someone tell me what I am missing. I get this feeling its a very basic thing that I have overlooked!
Your "child" package is defined as "main". I'm not even sure how it complied, let alone run to the point of showing the error message you got.
I believe the code below should do what you expected.
(I also took the liberty to rename the classes to use CamelCase (with initial caps) to adhere to best practices and to be easier to distinguish from variable names.)
Main.as
package {
public class Main extends MovieClip {
public function Main() {
var child:ChildMC = new ChildMC();
child.main = this;
}
public function callFunction():void {
trace("Done it");
}
}
}
EDIT: I just saw your comment that points out that child_mc is a MovieClip in the Library. I guess then that the child class is set as the Base Class of the child_mc?
If so, you cannot pass properties through the instantiator, you need to find another way to pass along the instance of the Main class to the Child class.
One way would be to add a setter, like the following:
Child.as (Base Class for ChildMC)
package {
public class Child extends MovieClip {
private var _main:Main;
public function Child() {
}
public function set main(main:Main):void {
this._main = main;
this._main.callFunction();
}
}
}

Saving static instance of Main - Actionscript 3

So I need to access information from my document(Main.as) class.
I tried making this easy by saving a static instance of my Main class.
private static var _instance:Main;
public static function get instance():Main { return _instance; }
public function Main() {
_instance = this;
}
Then when in another class I try to use this I get a null reference error.
public function InputController():void {
main = Main.instance;
main.stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyPress);
main.stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyRelease);
}
I get an error on the main.stage.addEventListener lines.
If you have timeline coding, you can instantiate your static variable with _instance=this (should be accessible, as main timeline is a part of document class) at the first keyframe, and reference there from elsewhere via property.
You are trying to return an instance without instantiating it. Use the following code for instantiating the class first.
private static var _instance:Main;
public static function get instance():Main
{
if(_instance == null)
_instance = new Main();
return _instance;
}

How to Make Popup window as Global in Flex?

Actually in my Flex Application have Some Popup windows and i want take some values in this Popup Window But The Values are Comming NULL
So how to Make a PopUp Window as Global? Because we are Using the values Globally.
Please Give Suggestion...
Edit
I'm Edit with some code...
Main.mxml(Main Aplication), Demo1.mxml(PopUpWindow), Demo2.mxml(PopUpWindow)
Now in Demo1.mxml have variable like...
[Bindable]private var arrayC:ArrayCollection=new ArrayCollection();//Hear Some value their.
NOw i want Use arrayC in Demo2.mxml then ..
public var variable1:Demo1=new Demo1();
var ac:ArrayCollection = new ArrayCollection();
ac = variable1.arrayC;
But hear ac contain Null Value Why?
Then,Now i'm Thinking Demo2.mxml(PopUpWindow) is Converting To Global Scope so it's value Used in Any Where .
Null because of you are tried create new instance so that each instance having their own state.
Also i bet you can't access arrayC ArrayCollection variable declared as private so you can't acccess.
Need to follow few steps
[Bindable]public var arrayC:ArrayCollection=new ArrayCollection(); //Make public variable
Use Singleton Class for you application
package com.foo.bar {
public class Model {
private static var instance : Model;
public function Model( enforcer : SingletonEnforcer ) {}
public static function getInstance() : Model {
if (!instance) {
instance = new Model( new SingletonEnforcer() );
}
return instance;
}
public var arrayC:ArrayCollection = new ArrayCollection();
}
}
class SingletonEnforcer{}
For more details Singleton pattern
private var popup:Demo1;
popup = PopUpManager.createPopUp(this,Demo1,true) as Demo1;
popup.arrayC = Model.getInstance().arrayC; // Here set value from Model class
PopUpManager.centerPopUp(popup);
Suppose you tried to access demo1.mxml arrayC variable in Demo2.mxml
var demo1_arrayC = Model.getInstance().arrayC;
Note that you can access arrayC arraycollection anywhere in your application like Demo2.mxml,Demo3...etc.
But better we have to avoid Singleton Class (unit test diffcult ..etc).
If you are using the values Globally, then no matter what you mean by the "Make a PopUp Window as Global", I strongly suspect that you would be best served by a singleton event dispatcher.
package com.example.demo.models {
import flash.events.IEventDispatcher;
import flash.events.EventDispatcher;
[Bindable]
class MyGlobalStuff extends EventDispatcher {
public var someGlobalValue:*;
private var _instance:MyGlobalStuff;
public function MyGlobalStuff (lock:SingletonLock, target:IEventDispatcher=null) {
super(target);
if(!(lock is SingletonLock)) {
throw(new Error("MyGlobalStuff is a singleton, please do not make foreign instances of it"));
}
}
public static function getInstance():MyGlobalStuff {
if(!_instance) {
_instance = new MyGlobalStuff (new SingletonLock());
}
return _instance;
}
}
}
class SingletonLock{}
The idea is this: that you would bind in your popup to
{myStuffModel.someGlobalValue}
myStuffModel would be initialized in your mxml as:
protected var myStuffModel:MyStuffModel = MyStuffModel.getInstance();
then in any other class throughout your application you can bind to or access the EXACT same data via the singleton model.

Re-defining named functions at runtime

What I am trying to do is kind of odd, but I am wondering if anyone can come up with a clever way to do what I want to do. Basically, I want to re-define a named function at runtime. I can do this with anonymous functions, but I can't figure out a way to do it for named functions. I want to do this so that I can implement a "spy" functionality on an object for a testing framework (a port of Jasmine to Flex).
Take, for instance, this class:
public class TestClass
{
public var anonymous:Function = function():void {
trace("original anonymous");
};
public function named():void {
trace("original named");
}
}
I can easily re-define the anonymous function because it is just a variable. Javascript uses this idiom a lot.
var testClass:TestClass = new TestClass();
testClass.anonymous = function():void { trace("overridden anonymous"); }
BUT, when I do the same thing for named functions, you get a compile-time error:
// Does not compile
testClass.named = function():void { trace("overridden named"); }
I tried to make it a bit more "squishy" but this leads to a runtime failure "Cannot assign to a method named on TestClass".
// Compiles with runtime failure
testClass["named"] = function():void { trace("overridden named"); }
Can anyone more clever than I come up with a way to hack this? Can the bytecode be hijacked? Something?
I want to modify an object, not a
class
But object doesn't contain functions, only non-static variables. I tried to use prototype property and replace method there, but original method still gets called instead of injected one.
About "hack" bytecode, do you mean "hack" already loaded SWF in runtime? I think it's not possible. I'm sure, though, you can parse SWF with something like as3swf, find method in bytecode, replace it and save result in new SWF.
I had an idea bout making a function "cache" . This might work with what you need.
Let's say you have a class "Car" with a method you need to redefine at runtime:
public class Car extends Sprite
{
private var functionCache:Function;
public function Car()
{
super();
}
public function flexibleFunction(functionBody:*=null):void{
if(functionBody is Function){
functionBody.call();
functionCache=functionBody;
} else {
functionCache(functionBody);
}
}
}
Usage:
public class Main extends Sprite
{
private var car:Car;
public function Main()
{
car = new Car();
car.flexibleFunction(function(){trace("redefine test #1")});
car.flexibleFunction();
car.flexibleFunction(function(doParametersWork:String="let's see"){trace("redefine test #2: " + doParametersWork);});
car.flexibleFunction("yes they do");
car.flexibleFunction();
}
}
an easy way to accomplish what you want is to simply pass a new function to the original function and execute it from there:
package
{
//Imports
import flash.display.Sprite;
//Class
public class RedefineFunction extends Sprite
{
//Constructor
public function RedefineFunction()
{
originalFunction();
originalFunction(redefinedFunction);
}
//Original Function
public function originalFunction(redefinition:Function = null):void
{
if (redefinition != null)
redefinition();
else
trace("Original Function Definition");
}
//Redefined Function
private function redefinedFunction():void
{
trace("Redefined Function Definition")
}
}
}
traces:
Original Function Definition
Redefined Function Definition