Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Call a method inside another method

I have a simple app, that triggers a boolean and sets a task to completed:

But I want to be able use a "Complete All" Button and set every task to complete. This here works fine:

  completeAll: function() {
    this.tasks.forEach(function(task) {
      task.completed = true;
    });
  },

http://codepen.io/anon/pen/avzMYr

But instead of setting it directly, I would like to use a method that is called like this, because I have a lot of other code that needs to be separated.

  completeTask: function(task) {
    task.completed = true;
  },

  completeAll: function() {
    this.tasks.forEach(function(task) {
      this.completeTask(task);
    });
  },

Yet this does not work, see here:

http://codepen.io/anon/pen/EVaMLJ

Any idea how to call the "completeTask(task)" method inside of the completeAll method?

like image 656
LoveAndHappiness Avatar asked Apr 15 '26 15:04

LoveAndHappiness


2 Answers

Your problem is that the value of this inside the .forEach() callback is not the same as what it is outside. You can save the outer value of this and then use that saved version to get what you want:

  completeAll: function() {
    var self = this;
    this.tasks.forEach(function(task) {
      self.completeTask(task);
    });
  },
like image 169
Pointy Avatar answered Apr 18 '26 07:04

Pointy


You could use Bind for setting the this value in methods like this:

completeAll: function() {
  this.tasks.forEach(function(task) {
    this.completeTask(task);
  }.bind(this));
}
like image 38
Pantelis Peslis Avatar answered Apr 18 '26 05:04

Pantelis Peslis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!