0

I have the following function with a number of bindings...

showDialog: function(data) {
  var dialog = new dialog({
    onOk: function(text) {

      var obj = {
        data: text.data
      };

      this.model.save(obj, {
        method: 'PUT',
        success: function() {
          this.success().bind(this)
        }.bind(this)
      });
    }.bind(this)
  });
  Main.dialogArea.show(dialog);
}

Though the code works, it throws the following error in the console...

Uncaught TypeError: Cannot read property 'bind' of undefined

The error has to do with the following line this.success().bind(this).

I realized that this gets fixed if I use var self = this instead...

showDialog: function(data) {
  var self = this;
  var dialog = new dialog({
    onOk: function(text) {

      var obj = {
        data: text.data
      };

      self.model.save(obj, {
        method: 'PUT',
        success: function() {
          self.success()
        }
      });
    }
  });
  Main.dialogArea.show(dialog);
}

If I do this, the error disappears. Any idea as to why that is? Shouldn't both cases work the same? I am not using ES6 so I cannot use arrow functions, I would like to use bind().

1 Answer 1

2

It should be

this.success.bind(this)

Instead of this.success().bind(this). Currently you're calling the function, function returns undefined and you're invoking .bind on it.

Side note:

Since you're doing

success: function() {}.bind(this)

You shouldn't have to bind a direct method invocation inside it, i.e

success: function() {
   this.success();
}.bind(this)

Should work, or just

success: this.success.bind(this)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.