Animate CC HTML5 canvas: how do I create a private/local variable in Actionscript? - html

I'm using a variable to create a toggle-effect on a function. The only problem is that this code changes the variable globally, and not locally for each object using the function. I know what I have to do, just not how :)
Function:
var count;
function animateTarget($target, $rwFrame) {
this.count = false;
if(!count == true)
{
$target.gotoAndPlay(2);
count=true;
}
else
{
$target.gotoAndPlay($rwFrame); //playback from a different frame
count=false;
}
}
Call:
this.Foo_Btn.addEventListener("click", animateTarget.bind(this, this.Foo_target, 34));

Actually, I got the answer from a friend (here with some updated variable names). Since it's JS, it reads the "clicked" as false, even though this is not stated. And by binding it to the object targetit will check for each separate object that uses this function.
var clicked;
function animateTarget(target, rwFrame) {
if(!target.clicked)
{
target.gotoAndPlay(2);
target.clicked = true;
}
else
{
target.gotoAndPlay(rwFrame);
}
}

Related

requestAnimationFrame type error in object

hi i'm trying to use requestAnimationFrame for my game and I actually use this code below, but as you can see ".bind()" create every loop a new function that slow down my game... I'm looking for a "efficient" solution for the best perfomance, thank you in advance :D
function myClass() {
this.loop = function() {
window.requestAnimationFrame(this.loop.bind(this));
/* here myGameLoop */
}
this.loop();
}
above code works but is slow.. instead this "standard" code give me "Type error":
window.requestAnimationFrame(this);
I have also found e tried this Q&A: requestAnimationFrame attached to App object not Window works just ONE time then give the same "Type error" :(
try if you don't believe me: http://jsfiddle.net/ygree/1 :'(
Without knowing the whole story of your object (what else is in there); you could simplify life by just doing this:
function myClass() {
var iHavAccessToThis = 1;
function loop() {
iHavAccessToThis++;
/* here myGameLoop */
requestAnimationFrame(loop);
}
loop();
//if you need a method to start externally use this instead of the above line
this.start = function() { loop() }
//...
return this;
}
Now you don't need to bind anything and you access local scope which is fast.
And then call:
var class1 = new myClass();
class1.start();

AS3 Passing Variable Parameters to a generic Function Menu / SubItems

I'm no code genius, but a fan of action script.
Can you help me on this:
I have a function that depending on the object selected, will call event listeners to a set of 'sub-items' that are already on stage (I want to reuse this subitems with changed parameters upon click, instead of creating several instances and several code).
So for each selected 'case' I have to pass diferent variables to those 'sub-items', like this:
function fooMenu(event:MouseEvent):void {
switch (event.currentTarget.name)
{
case "btUa1" :
trace(event.currentTarget.name);
// a bunch of code goes here
//(just cleaned to easy the view)
/*
HELP HERE <--
here is a way to pass the variables to those subitems
*/
break;
}
}
function fooSub(event:MouseEvent):void
{
trace(event.target.data);
trace(event.currentTarget.name);
// HELP PLEASE <-> How can I access the variables that I need here ?
}
btUa1.addEventListener(MouseEvent.CLICK, fooMenu);
btUa2.addEventListener(MouseEvent.CLICK, fooMenu);
btTextos.addEventListener(MouseEvent.CLICK, fooSub);
btLegislacao.addEventListener(MouseEvent.CLICK, fooSub);
Anyone to help me please?
Thank very much in advance. :)
(I'm not sure I got your question right, and I haven't developed in AS3 for a while.)
If you want to simply create function with parameters which will be called upon a click (or other event) you can simply use this:
btUa1.addEventListener(MouseEvent.CLICK, function() {
fooMenu(parameters);
});
btUa2.addEventListener(MouseEvent.CLICK, function() {
fooMenu(other_parameters)
}):
public function fooMenu(...rest):void {
for(var i:uint = 0; i < rest.length; i++)
{
// creating elements
}
}
If you want to call event listeners assigned to something else you can use DispatchEvent
btnTextos.dispatchEvent(new MouseEvent(MouseEvent.CLICK))
Remember, you can't use btTextos.addEventListener(MouseEvent.CLICK, carregaConteudo("jocasta")); because the 2nd parameter you pass while adding Eventlistener will be considered as function itself - there are two proper ways to use addEventListener:
1:
function doSomething(event:MouseEvent):void
{
// function code
}
element.addEventListener(MouseEvent.CLICK, doSomething); //notice no brackets
2:
element.addEventListener(MouseEvent.CLICK, function() { // function code });
So:
function fooSub(event:MouseEvent, bla:String):void
{
trace(event.currentTarget.name+" - "+bla);
// bla would be a clip name.
}
codebtTextos.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) { fooSub(e, "jocasta") } );
Or try something like this if you want content to be dynamically generated:
btUa1.addEventListener(MouseEvent.CLICK, function() {
createMenu(1);
});
btUa2.addEventListener(MouseEvent.CLICK, function() {
createMenu(2);
});
function createMenu(id):void
{
// Switching submenu elements
switch (id)
{
case 1:
createSubmenu([myFunc1, myFunc2, myFunc3]); // dynamically creating submenus in case you need more of them than u already have
break;
case 2:
createSubmenu([myFunc4, myFunc5, myFunc6, myFunc7]);
break;
default:
[ and so on ..]
}
}
function createSubmenu(...rest):void {
for (var i:uint = 0; i < rest.length; i++)
{
var mc:SubItem = new SubItem(); // Subitem should be an MovieClip in library exported for ActionScript
mc.addEventListener(MouseEvent.CLICK, rest[i] as function)
mc.x = i * 100;
mc.y = 0;
this.addChild(mc);
}
}
Your question is rather vague; what "variables" do you want to "pass"? And what do you mean by "passing the variable to a sub item"? Usually "passing" means invoking a function.
If you can be more specific on what exactly your trying to do that would be helpful. In the meantime, here are three things that may get at what you want:
You can get any member of any object using bracket notation.
var mc:MovieClip = someMovieClip;
var xVal:Number = mc.x; // The obvious way
xVal = mc["x"]; // This works too
var propName:String = "x";
xVal = mc[propName] ; // So does this.
You can refer to functions using variables
function echo(message:String):void {
trace(message);
}
echo("Hello"); // The normal way
var f:Function = echo;
f("Hello"); // This also works
You can call a function with all the arguments in an array using function.apply
// Extending the above example...
var fArgs:Array = ["Hello"];
f.apply(fArgs); // This does the same thing
Between these three things (and the rest parameter noted by another poster) you can write some very flexible code. Dynamic code comes at a performance cost for sure, but as long as the frequency of calls is a few hundred times per second or less you'll never notice the difference.

Call two function in one onchange = not working

I have been searching how to put more than one function in onchange and I found how something like this for example: onchange = "function1(); function2();".
My problem here is I have followed what does the example like, but only function1 is working, function2 is not working. If I make it otherwise to onchange = "function2(); function1();", only function2 is working, function1 is not working, the same.
Any ideas guys?
Thanks.
The functions, I used Ajax:
function1(test)
{
var kode = test.value;
if (!kode) return;
xmlhttp.open('get', '../template/get_name-opr.php?kode='+kode, true);
xmlhttp.onreadystatechange = function() {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
{
//alert(kode);
document.getElementById("code").innerHTML = xmlhttp.responseText;
}
return false;
}
xmlhttp.send(null);
}
function2(test)
{
var kode = test.value;
if (!kode) return;
xmlhttp**1**.open('get', '../template/get_name2-opr.php?kode='+kode, true);
xmlhttp**1**.onreadystatechange = function() {
if ((xmlhttp**1**.readyState == 4) && (xmlhttp**1**.status == 200))
{
//alert(kode);
document.getElementById("code2").innerHTML = xmlhttp**1**.responseText;
}
return false;
}
xmlhttp**1**.send(null);
}
To solve my problem, I created two xmlhttp different. (xmlhttp and xmlhttp1).
Go through the link I gave, it seems to be problem with the way you are managing the xmlhttprequest objects, manage their instances properly, in your case because you are using the same xmlhttprequest for two simultaneous AJAX requests, only one of them is getting served. Either wait for one of them to get served or create two instances of the xmlhttprequest.
The statement xmlhttp.readystate = function() {...} obviously replaces the readystate property of that xmlhttprequest object, so on your second function, that is being replaced( because you are using the xmlhttprequest for both of them ). This is why you are seeing the funny behaviour.
Call function2() at the end of function1().
onchange = "function1()"
function1(){
...
function1 body;
...
function2()
}
Wrap the two function calls in one and call that function!
function myFirstFunction() {
//body
}
function mySecondFunction() {
//body
}
//Call this guy.
function myWrappedFunction() {
myFirstFunction();
mySecondFunction();
}

How to Getting the Variable from Function in as3 without using get ,set method?

Hai am Getting trouble to retrive the values from function(addText).i Called from another function onFullScreen().I dont know how Can i do this,Kindly Help me?Here i attach my Code
private function addText()
{
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, ncOnStatus);
function ncOnStatus(infoObject:NetStatusEvent)
{
trace("nc: "+infoObject.info.code+" ("+infoObject.info.description+")");
if (infoObject.info.code == "NetConnection.Connect.Success")
{
initSharedObject(chatSharedObjectName);
}
}
function formatMessage(chatData:Object)
{
trace("room"+chatData.message);
number = chatData.txtalign;//i want to retrive the value of number
number.toString();
return number;
}
function syncEventHandler(ev:SyncEvent)
{
var infoObj:Object = ev.changeList;
// if first time only show last 4 messages in the list
if (lastChatId == 0)
{
lastChatId = Number(textchat_so.data["lastChatId"]) - 1;
if (lastChatId < 0)
lastChatId = 0;
}
}
function connectSharedObject(soName:String)
{
textchat_so = SharedObject.getRemote(soName, nc.uri)
// add new message to the chat box as they come in
textchat_so.addEventListener(SyncEvent.SYNC, syncEventHandler)
textchat_so.connect(nc)
}
function connectSharedObjectRes(soName:String)
{
connectSharedObject(soName)
trace(soName)
}
function initSharedObject(soName:String)
{
// initialize the shared object server side
nc.call("initSharedObject", new Responder(connectSharedObjectRes), soName)
}
}
i using the variable in another function ,but I cannot retrive the Value.
private function onFullScreen(event:FullScreenEvent):void
{
mediaContainer.addMediaElement(alert);
alert.alert("Error",number);// if i cannot retrive the value hnumber here
}
The addText() method is asynchronous, meaning that you can't simply call it , you need to wait for the event listener to return a value.
I'm not sure why you would feel the need to enclose all these functions, it's not very legible and I doubt it's necessary. You're also missing quite a few semi colons...
In any case , I couldn't see where the formatMessage() method was called, it seems that's the only place where the "number" variable gets defined.
You could create a variable outside the scope of the functions.
private var num:int;
Then in your addText function, assign a value to the variable:
num = infoObject.info.code;
Then in your onFullScreen function, access the num variable:
alert.alert("Error", num);

manually set check box selected in as3

I have a CheckBox in as3 that i need to set as checked with code. Do I dispatch an event? If so, how do I create an event, and give it a target (target is read only). Or is there another way to do it? thanks.
my_checkbox.selected = true;
And of course:
my_checkbox.selected = false;
To handle the box being checked/unchecked:
my_checkbox.addEventListener(MouseEvent.CLICK, _selected);
function _selected(e:MouseEvent):void
{
var bool:Boolean = e.target.selected;
if(bool)
{
trace("was checked");
// more code
}
else
{
trace("was unchecked");
// more code
}
}