Calling local class - actionscript-3

I'm trying to call a static method from a class called "JSON", however the import I'm doing already has this method. How can I call a local class?
I've tried this:
mypackage.subpackage.JSON.encode(param1)
In C # the above would work, but I do not know why in ActionScript below does not work.
import flash.utils.ByteArray;
public class Package extends ByteArray
{
public function writeJsonObject(param1:Object) : void
{
this.writeUTF(JSON.encode(param1));
}
}
I get this error:
Error: 1061: Call to a possibly undefined method decode through a reference with static type Class

Try using JSON.stringify()
import flash.utils.ByteArray;
public class MyClass extends ByteArray
{
public function writeJsonObject(param1:Object) : void
{
this.writeUTF(JSON.stringify(param1));
}
}
Reference: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html
Also worth noting the difference between writeUTF and writeUTFBytes to understand exactly what's getting written to your ByteArray

Related

How do I mock a static method call from a nother static method in the same class?

I have a utilities class wherein one static method calls another. I want to mock the called method but not the target method. Does anyone have an example?
I've got:
#RunWith(PowerMockRunner.class)
#PrepareForTest({SubjectUnderTest.class})
public class SubjectUnderTestTest {
...
SubjectUnderTest testTarget = PowerMockito.mock(SubjectUnderTest.class, Mockito.CALLS_REAL_METHODS);
Starting from the docs, with some minor tweaks, you can either mock or spy the static method, depending on what you need (spying seems a bit less verbose but has different syntax). You can find below a sample for both, based on PowerMockito 1.7.3 & Mockito 1.10.19.
Given the following simple class with the required 2 static methods:
public class ClassWithStaticMethods {
public static String doSomething() {
throw new UnsupportedOperationException("Nope!");
}
public static String callDoSomething() {
return doSomething();
}
}
You can do something like:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.*;
// prep for the magic show
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassWithStaticMethods.class)
public class ClassWithStaticMethodsTest {
#Test
public void shouldMockStaticMethod() {
// enable static mocking
mockStatic(ClassWithStaticMethods.class);
// mock the desired method
when(ClassWithStaticMethods.doSomething()).thenReturn("Did something!");
// can't use Mockito.CALLS_REAL_METHODS, so work around it
when(ClassWithStaticMethods.callDoSomething()).thenCallRealMethod();
// validate results
assertThat(ClassWithStaticMethods.callDoSomething(), is("Did something!"));
}
#Test
public void shouldSpyStaticMethod() throws Exception {
// enable static spying
spy(ClassWithStaticMethods.class);
// mock the desired method - pay attention to the different syntax
doReturn("Did something!").when(ClassWithStaticMethods.class, "doSomething");
// validate
assertThat(ClassWithStaticMethods.callDoSomething(), is("Did something!"));
}
}

AS3 addEventListener not a recognized method in my custom class

I want to have a Class called Commands that I can put different key presses and functions into that will control game states and variables for quick and easy game testing. I'm trying this, but it's not working...
package gameTesting {
import flash.events.KeyboardEvent;
import flash.events.*;
import flash.ui.Keyboard;
import flash.display.*;
import flash.events.EventDispatcher;
public class Commands {
public function Commands() {
addEventListeners();
}
public function addEventListeners():void{
addEventListener(KeyboardEvent.KEY_DOWN,keyDown);
}
public function keyDown(ke:KeyboardEvent):void{
trace("key pressed");
}
}
}
which throws this error:
C:...\Commands.as, Line 15, Column 4 1180: Call to a possibly undefined method addEventListener.
So, I tried having my class extend something that inherits the EventDispatcher methods:
//...
public class Commands extends DisplayObject{
// ...
but I just get this error thrown from my main .as file when trying to instantiate this Class:
ArgumentError: Error #2012: Commands$ class cannot be instantiated.
I also tried throwing the static keyword around just for lols, but no dice.
What am I missing here?
by the way, my reason for doing things this way is just so that I can remove this functionality (so users can't use it) by simply removing the line of code that instantiates this class. I think it's pretty nifty, but if this seems asinine, by all means speak up!
Try to pass stage to Commands,so you can add addEventListener on stage.
import flash.display.Stage;
public class Commands {
public function Commands(stage:Stage) {
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDown);
}
public function keyDown(ke:KeyboardEvent):void{
trace("key pressed");
}
}

Flash AS3 - Trying to access public function from another class throws error?

This is my Main.as:
package {
import flash.display.MovieClip;
public class Main extends MovieClip {
public function Main() {
// Code here
}
public function myFunc() {
trace('!!!!');
}
}
}
When I try accessing it from another class using the following code, Flash throws me Error #2136:
package {
import flash.display.MovieClip;
import Main;
public class MyClass extends MovieClip {
public var m:Main;
public function MyClass() {
m = new Main();
m.myFunc();
}
}
}
EDIT: One more thing. The second class is attached to a MovieClip and exported on the first frame. I thought it made no difference, but someone in the comments have told me it does and apparently that's what's causing the error in the first place. In that case, how can I access the public function from a class attached to a MC?
Next time post the error message itself, most of us do not have Flash errors memorized by id. ;)
From the docs:
2136 The SWF file %1 contains invalid data.
This rings a bell for me. Your Main class is probably your document class. The document class is a special class that cannot be instantiated.
To access properties and methods of the document class instance from other code, you simply need a reference to the document class instance.
There are many ways you could get a reference, as it is really just a code dependency design question. Two common, easy solutions are:
1. Use the root property of any display object that is added as a child of the document class instance. Since the root property is typed to DisplayObject you need to cast to your document class to access its methods and property, for example: Main(root).myFunc().
2. Use the singleton pattern and assign a static public reference to the document class instance:
public class Main {
public static var main:Main;
public function Main() {
main = this;
}
public function myFunc():void { }
}
// usage:
Main.main.myFunc();

Getting error Type 1061: Call to a possibly undefined method addEventListener through a reference with static type

I moved my code from my Application to a separate AS class file and now I'm getting the following errors:
1061: Call to a possibly undefined method addEventListener through a reference with static type Class.
1180: Call to a possibly undefined method addEventListener.
.
package managers {
import flash.events.Event;
import flash.events.EventDispatcher;
public class RemoteManager extends EventDispatcher {
public function RemoteManager() {
}
public static function init(clearCache:Boolean = false):void {
addEventListener(SETTINGS_CHANGE, settingChangeHandler);
addEventListener(ITEMS_UPDATED, itemsUpdatedHandler);
}
}
}
Your code
addEventListener(SETTINGS_CHANGE, settingChangeHandler);
evaluates to
this.addEventListener(SETTINGS_CHANGE, settingChangeHandler);
There is no this in a static method, since it's designed to function without an instance. Furthermore, you cannot attach an event listener and dispatch events from a static class.
Either change your function declaration to
public function init(clearCache:Boolean = false):void
Or implement a singleton pattern to kinda get a "static class, that dispatches events".
Singleton with event management.
You have declared your method init as static , so all you can use into this one is static field, static method, no object that belong to the instance.
Remove the static from the function or try to implements a singleton if it what you are after.
here a quick really simple one :
public class RemoteManager extends EventDispatcher {
private static var _instance:RemoteManager;
public function static getInstance():RemoteManager{
if (_instance == null) _instance=new RemoteManager();
return _instance;
}
public function RemoteManager() {
if (_instance != null) throw new Error("use getInstance");
}
public static function init(clearCache:Boolean = false):void {
getInstance().addEventListener(SETTINGS_CHANGE, settingChangeHandler);
getInstance().addEventListener(ITEMS_UPDATED, itemsUpdatedHandler);
}
}
// use it
RemoteManager.init();

Writing objects to socket in AS3/actionscript?

I am trying to pass object to the server through socket connection in actionscript 3. What is the best way to do that?
is serialization better?
or should I encode it first and then sent it as string?
please help me to understand this?
thank you
If your object is implementing IExternalizable and you call registerClassAlias you are safe to use readObject and writeObject. Note however that no constructor parameters are allowed when implementing IExternalizable.
For instance:
package {
import flash.net.*;
import flash.utils.*;
public class Foo implements IExternalizable {
registerClassAlias("Foo", Foo);
public var bar: String;
public function Foo() { // No constructor parameters allowed.
}
public function writeExternal(output: IDataOutput): void { output.writeUTF(bar); }
public function readExternal(input: IDataInput): void { bar = input.readUTF(); }
}
}
You are then safe to call readObject and writeObject on any IDataOutput or IDataInput which is for instance a Socket, ByteArray or URLStream.