0

I am using easeljs for a HTML5 game.

I am calling onClick from within a method in a class, but the event object is overwriting my 'this' object so I can no longer access the other class methods or vars. For example I have something like (obviously this is not the actual code, just a quick illustration):

function Book(){

  this.text = "this is the text";

  this.makeText = function(){
            //Define some shapes
            var character = new Container();
            character.addChild(some shapes);
            character.onClick = this.detectClick;
  }

  this.detectClick = function(){
           alert(this.text);
  }
}

So, if I run this, I would get an undefined alert because in my detectClick method, this is now my event object.

So how do I call the original text from within this method?

Many Thanks

karatecode
  • 574
  • 6
  • 21

4 Answers4

3

You need to us closure to pass the object reference

 var self = this;
 character.onClick = function(){ self.detectClick() };
nxtwrld
  • 1,942
  • 14
  • 15
0

Or use a simple proxy method.

function proxy(method, scope) {
    return function() {
        return method.apply(scope, params);
    }
}
character.onclick = proxy(detectClick, this);
Lanny
  • 11,244
  • 1
  • 22
  • 30
0

Ok that you really need to do is

function Book(){

  this.text = "this is the text";

  this.makeText = function(){
            //Define some shapes
            var character = new Container();
            character.addChild(some shapes);
            character.onClick = this.detectClick.bind(this);
  }

  this.detectClick = function(){
           alert(this.text);
  }
}
Vartan Arabyan
  • 2,925
  • 7
  • 25
  • 35
0

scope of 'this' is the problem in your code. Change your code like the below code

 function Book(){

  this.text = "this is the text";
  var that=this;
  this.makeText = function(){
        //Define some shapes
        var character = new Container();
        character.addChild(some shapes);
        character.onClick = that.detectClick;
 }

 this.detectClick = function(){
       alert(this.text);
 }
}
Villan
  • 730
  • 1
  • 8
  • 26