I'm using typescript and knockoutjs. On a <select>
value change, I need to call a function called updateCities.
I get this error in the console:
Uncaught TypeError: this.updateCities is not a function
Here is my code:
class HomeViewModel {
_countries = ko.observableArray();
_regions = ko.observableArray();
selectedCountry = ko.observable();
constructor(allCountries) {
for (var index = 0; index < allCountries.length; index++) {
this._countries.push(allCountries[index].country);
}
this.selectedCountry.subscribe(function (newValue){
this.updateCities();
}) //this is where it sets the function to call on value change
}
updateCities() {
$.ajax({
url: `http://api.geonames.org/children?geonameId=${selectedCountry}&username=elion`
}).then(function(allCitiesXML) {
var allCitiesJSON = xml2json(allCitiesXML);
var allCities = JSON.parse(allCitiesJSON);
for (var index = 0; index < allCities.length; index++) {
this._regions.push(allCities[index]);
}
});
}
}
When I view the generated javascript file, I see that updateCountries is outside of the scope of this
. Here is the generated javascript file:
var HomeViewModel = (function () {
function HomeViewModel(allCountries) {
this._countries = ko.observableArray();
this._regions = ko.observableArray();
this.selectedCountry = ko.observable();
for (var index = 0; index < allCountries.length; index++) {
this._countries.push(allCountries[index].country);
}
this.selectedCountry.subscribe(function (newValue) {
this.updateCities();
});
}
HomeViewModel.prototype.updateCities = function () {
$.ajax({
url: "http://api.geonames.org/children?geonameId=" + selectedCountry + "&username=elion"
}).then(function (allCitiesXML) {
var allCitiesJSON = xml2json(allCitiesXML);
var allCities = JSON.parse(allCitiesJSON);
for (var index = 0; index < allCities.length; index++) {
this._regions.push(allCities[index]);
}
});
};
return HomeViewModel;
})();
How do I cause the generated javascript file to call updateCities properly?