Sorry, I was in a rush before and missed some stuff…
Basically you need to first of all get the checked status using: event.target.checked not with this.checked. Try out these two variations to see how they behave differently in regards to context/this. Check the console output for each.
This won’t work, “this” is pointing at the window object because you’re using an arrow function.
Template.task.events({
'click .toggle-checked': (event) => {
console.log('Context:', this);
console.log('Checked:', event.target.checked);
Tasks.update(this._id, {
$set: { checked: event.target.checked },
});
}
});
Without using an arrow function, “this” points where it should, rather than window:
Template.task.events({
'click .toggle-checked': function(event) {
console.log('Context:', this);
console.log('Checked:', event.target.checked);
Tasks.update(this._id, {
$set: { checked: event.target.checked },
});
}
});
Still not using an arrow function, but using ES6 shorthand “this” again points where it should:
Template.task.events({
'click .toggle-checked'(event) {
console.log('Context:', this);
console.log('Checked:', event.target.checked);
Tasks.update(this._id, {
$set: { checked: event.target.checked },
});
}
});
But you cannot use arrow functions in this situation.
As a summary you were making two mistakes:
- Using arrow functions caused this to point to window.
- You were checking on this.checked for the checked status when you should be checking event.target.checked. this.checked would get the value from the database, which presumably is why you were notting the value before setting it again, but IMHO you should just set true or false based on the actual value from your checkbox which is on event.target.checked.
Your update call was failing to do what you expected because this._id was undefined due to this pointing at window.
Hope that helps.