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?
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);
});
},
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With