Jump to content

Variable with Multiple Values


A.Russell
 Share

Recommended Posts

I want to use a variable across the scope of a class. How do I do this without it having different values in different methods? 

 

Why can a variable declared at class level have a different value depending on the method?: 

 

class variableProblem extends Phaser.Sprite{isMoving: boolean = false;//some code hereeventDragStart() {            this.isMoving = true; <-- sets isMoving to true, though it is undefined on first run (should be false first run)        }update() {            if (this.isMoving) {    <-- isMoving is always false!                 this.bringToTop();                this.isMoving = false;            }}

isMoving has a different value in eventDragStart() to update(). This shouldn't be possible, so I guess it has something to do with the way it compiles to Javascript. 

 

However, I really need only one instance of isMoving in this class, and it is very frustrating. How do I make this work? 

Link to comment
Share on other sites

Zoombox: adding var in front makes a syntax error. I am coding in Typescript.

 

XekeDeath: I thought of that, though I can't see what else "this" could be other than the same instance of this object. The event is declared as:

 

this.events.onDragStart.add(this.eventDragStart);

 

I even tried creating getter and setter methods. Though if I try to call them from within eventDragStart, I get an error at runtime. It's as if the callback functions don't exist in the same class.

 

setIsMoving(val: boolean) {
            this.isMoving = val;
        }
 
        getIsMoving(): boolean{
            return this.isMoving;
        }
 
        eventDragStart() {
            this.setIsMoving(true);  <-- JavaScript runtime error: Object doesn't support property or method 'setIsMoving'

        }

 

I additionally specified  isMoving to be private. Fiurthermore, I checked the super class, and it doesn't have a variable called isMoving that it might be conflicting with. 

 

So, I' stumped. Any other ideas?

Link to comment
Share on other sites

Yup, take a closer look at onDragStart... It is a Phaser.Signal, and you are calling the add() function on it...

That takes 2 arguments: The function to call, and the context to call it on...

You are only supplying the function to call, try adding "this" as a second argument, and see how things work...

this.events.onDragStart.add(this.eventDragStart, this);
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...