I am implementing a scenario in which on clicking outside the drawer, i want to execute the saveChange action but somehow it is giving me the error that saveChange is not a function. I tried different ways to set the context but it is not working.
JavaScript
x
30
30
1
export default class DrawerModel {
2
constructor(context) {
3
this.data = context.primaryInfoData;
4
this.name = ko.observable('test');
5
6
document.addEventListener("click", function (e) {
7
var self= this;
8
var element = e.target;
9
let isOutside = true;
10
for (var element = e.target; element; element = element.parentNode) {
11
if (element.id === 'drawer_primaryInfoDrawer') {
12
isOutside = false;
13
}
14
}
15
if(isOutside) {
16
self.saveChanges();
17
}
18
19
});
20
}
21
22
saveChanges() {
23
const data = {
24
title: this.name(),
25
}
26
this.data.valueChangeHandler(data);
27
};
28
29
}
30
Error :
JavaScript
1
2
1
Uncaught TypeError: self.saveChanges is not a function
2
Advertisement
Answer
this is because in your event listener, this
refers to the window instead of your class. you can fix this by adding .bind(this)
to your function like so:
JavaScript
1
4
1
document.addEventListener("click", function (e) {
2
// ...
3
}.bind(this));
4