1

I just to wanted to call a function inside a self-executing anonymous function. Whenever I try to call a function, I am getting an error saying "Uncaught TypeError: createGesture() is not a function"

loadGesturesFromDatabase: function() {
  var firebaseRef = new Firebase("https://test.firebaseio.com/");

  this.loadFromFireBase(firebaseRef);

  firebaseRef.on('value', function(dataSnapshot) {

    dataSnapshot.val();

    console.log(dataSnapshot.val()); // console showing the data                            //which fetched from firebase


    //Only having issue when executing following line of code

    this.loadJson(JSON.stringify(dataSnapshot.val()));

  });

}

loadJson: function(json) {

}
Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63
Shiran Gabriel
  • 440
  • 4
  • 15
  • Please show the full trace of the error. this inside the callback should be referring to firebaseRef which would not have load loadJson method. – rishabh dev Mar 12 '16 at 21:47
  • you are calling somewhere in your code an undefined function `createGesture`. Search your files for that and comment it. – Oden Mar 12 '16 at 21:47
  • Probably `this` is not what you expect it to be. Read [this](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – trincot Mar 12 '16 at 23:19

2 Answers2

4

The provided code is not much to go by, but the error is probably caused by the fact that you refer to this inside an anonymous function.

this.loadJson(JSON.stringify(dataSnapshot.val()));

Try storing the this out of the anonymous function, and then using it in the anonymous function, like so

loadGesturesFromDatabase: function () {
  var firebaseRef = new Firebase("https://test.firebaseio.com/");

  //We keep a reference to the correct this
  var _this = this;

  this.loadFromFireBase(firebaseRef);

  firebaseRef.on('value', function(dataSnapshot) {
      dataSnapshot.val();
      console.log(dataSnapshot.val()); // console showing the data                            //which fetched from firebase

      //You are now referencing the correct this
      _this.loadJson(JSON.stringify(dataSnapshot.val()));
    });
}

As a note, there are no self invoking functions in the code you provided. A self invoking function looks like this

(function() {
    //code
})()
Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63
2

Mitch identified the problem: since you have a callback function, the meaning of this changes. You can explicitly set the value of this by using bind():

firebaseRef.on('value', function(dataSnapshot) {
    this.loadJson(JSON.stringify(dataSnapshot.val()));
}.bind(this));

See: Use of the JavaScript 'bind' method

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807