简体   繁体   中英

Typescript - call child method from parent class

I am trying to call the child method from the abstract parent class in typescript. But i am getting this error:

Uncaught TypeError: this.activateMultiselect is not a function

How would I implement this without error?

Here is the code:

interface iGetAreas {
    _areasList: Array<string>;
    _areas: KnockoutObservableArray<string>;
    _selectedArea: KnockoutObservable<string>;
    getAreas(geonameId: string);
    activateMultiselect();
}

abstract class AreaGetter implements iGetAreas {
    _areasList = [];
    _areas = ko.observableArray([]);
    _selectedArea = ko.observable('');

    abstract activateMultiselect();

    getAreas(geonameId){
        var self = this;
        self._areasList = [];
        $.ajax({
            url: `http://api.geonames.org/children?geonameId=${geonameId}&username=elion`
        }).then(function(allAreasXML) {
            var allAreasJSON = xml2json(allAreasXML);
            var allAreas = JSON.parse(allAreasJSON);
            if(allAreas.geonames.length) {
                for (var index = 1; index < allAreas.geonames.length - 1; index++) {
                self._areasList.push(allAreas.geonames[index].geoname);
                }
            } else {
                if(allAreas.geonames) {
                    self._areasList.push(allAreas.geonames.geoname);
                }
            }
            self._areas(self._areasList);
            this.activateMultiselect();
        });
    }
}

class RegionGetter extends AreaGetter {
    activateMultiselect() {
        $("#region-select").multiselect({
            buttonWidth: '100%',
            buttonContainer: '<div style="height: 64px;" />',
            buttonClass: 'none',
            onChange: function(option, checked, select) {
                alert('Changed region option ' + $(option).val() + '.');
            }
        });
    }
}

class TownGetter extends AreaGetter {
    activateMultiselect() {
        $("#town-select").multiselect({
            buttonWidth: '100%',
            buttonContainer: '<div style="height: 64px;" />',
            buttonClass: 'none',
            onChange: function(option, checked, select) {
                alert('Changed town option ' + $(option).val() + '.');
            }
        });
    }
}

Uncaught TypeError: this.activateMultiselect is not a function

The error is not because of child classes not having the function. Its because you have the wrong this in:

this.activateMultiselect();

Fix :

self.activateMultiselect();

More

PS: recommend using an arrow function. https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM