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) {

}
3
  • Please show the full trace of the error. this inside the callback should be referring to firebaseRef which would not have load loadJson method. Mar 12, 2016 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, 2016 at 21:47
  • Probably this is not what you expect it to be. Read this
    – trincot
    Mar 12, 2016 at 23:19

2 Answers 2

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
})()
0
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.