i often have the problem that i cant reach the Functions of my js classes inside the js class.
I mostly fix it with this. or a bind(this) but why does this not work? its the exact copy the way i do this in another class.
class Page {
// constructor and props
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
filterItems["Control"].Items.push({
Template: function (itemElement) {
itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
this.ShowNewJobPopup(); // how is this not a function
}.bind(this)
});
}
});
return filterItems;
}
}
when im in the dev console. i can write Page.ShowNewJobPopup (Page is the script this is attached to)
>Solution :
The this is actually not from the class Page.
We rewrite your Page class in the below way and you can see the this is referred to the obj.
class Page {
constructor() {}
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
const obj = {
Template: function (itemElement) {
itemElement.append(
'<div id="btnNeuerJob" style="width: 100%; margin-top: 4px;"></div>'
);
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
this.ShowNewJobPopup();
}.bind(this), // this is referred to obj
});
},
};
filterItems["Control"].Items.push(obj);
return filterItems;
}
}
What you can do is create a variable self to store the this and use it to reference to the class Page later.
class Page {
constructor() {}
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
const self = this; // this here is referred to the class Page
const obj = {
Template: function (itemElement) {
itemElement.append(
'<div id="btnNeuerJob" style="width: 100%; margin-top: 4px;"></div>'
);
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
self.ShowNewJobPopup(); // self is referred to Page Class
},
});
},
};
filterItems["Control"].Items.push(obj);
return filterItems;
}
}