Jump to content

Input event on class


polo
 Share

Recommended Posts

I try to implement a input event handler from an class inherited of Sprite class. See below

 

Rts.Unit = function Unit(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'player');
    this.inputEnabled = true;
    this.selected = false;
    this.events.onInputDown.add(this.select);
    return this;
};
 
Rts.Unit.prototype = Object.create(Phaser.Sprite.prototype);
Rts.Unit.prototype.constructor = Rts.Unit;
 
Rts.Unit.prototype.dummy = function() {
    console.log("dummy");
}
 
Rts.Unit.prototype.select = function() {
    this.selected = true;
    this.dummy();
};
 
but it's doesnt work and raise error
"Uncaught TypeError: undefined is not a function"
 
My game is manage by state.
Regards

 

Link to comment
Share on other sites

Most often, when I get such errors, it's because 'this' is not what I expect it to be.

 

The development tools should tell you which line the error occurs in.  Put a "console.log(this);" in the line before and restart. The next time the error comes up, take a look what 'this' really is and if it has the method you want. For if 'this' is your gamestate-object and you expect it to be 'game', try "this.game" instead.

Link to comment
Share on other sites

Thanks , that's true "this" is not what i expected in this context, i don't understand why in the event context i can't use a self reference to an object function. Why the "event" works in game -state context ?

Link to comment
Share on other sites

Thanks , that's true "this" is not what i expected in this context, i don't understand why in the event context i can't use a self reference to an object function. Why the "event" works in game -state context ?

 

You can (as Lewester pointed out), it's just, that 'this' act's really strange or someone coming from other langages. These links might be of interest:

 

http://www.quirksmode.org/js/this.html

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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