我在打字稿中製作了此按鈕類。我已經給它一個「默認」函數來處理點擊事件。但是,如果我想要傳遞一個函數作爲參數並在點擊時調用傳遞的函數呢?重寫打字稿類中的默認功能
下面的代碼:
abstract class BaseButton {
element:HTMLElement;
label:string;
constructor(element:HTMLElement, label:string) {
console.log(this);
this.element = element;
this.label = label;
this.init();
}
init():void {
this.setText(this.label);
this.addListeners();
}
setText(label:string):void {
this.element.innerHTML = label;
}
kill():void {
this.removeListeners();
}
addListeners():void {
this.element.addEventListener("mouseover", this.onMouseOver);
this.element.addEventListener("click", this.onClick);
this.element.addEventListener("mouseout", this.onMouseOut);
this.element.addEventListener('touchstart', this.onTouchStart);
this.element.addEventListener('touchmove', this.onTouchMove);
this.element.addEventListener('touchcancel', this.onTouchCancel);
this.element.addEventListener('touchend', this.onTouchEnd);
}
removeListeners():void {
this.element.removeEventListener("mouseover", this.onMouseOver);
this.element.removeEventListener("click", this.onClick);
this.element.removeEventListener("mouseout", this.onMouseOut);
this.element.removeEventListener('touchstart', this.onTouchStart);
this.element.removeEventListener('touchmove', this.onTouchMove);
this.element.removeEventListener('touchcancel', this.onTouchCancel);
this.element.removeEventListener('touchend', this.onTouchEnd);
}
onTouchStart():void {
}
onTouchMove():void {
}
onTouchCancel():void {
}
onTouchEnd():void {
}
onMouseOver():void {
console.log('mouse over');
}
onMouseOut():void {
console.log('mouse out');
}
abstract onClick(event:Event):void
}
class Button extends BaseButton {
element:HTMLElement;
label:string;
callback:any;
constructor(element:HTMLElement, label:string, callback?:() => void) {
super(element,label);
this.element = element;
this.label = label;
this.callback = callback;
}
onClick(event:Event):void {
if (this.callback) {
console.log('ddd');
this.callback();
}
}
}
const el = document.getElementById('btn');
const button = new Button(el,'Click');
const ell = document.getElementById('btnn');
const buttonn = new Button(ell,'Click');
const elll = document.getElementById('btnnn');
const buttonnn = new Button(elll,'Click',() => {
alert('fff');
});
嗨,謝謝!也許我還不夠清楚。我想要做的就是重載點擊按鈕,如果點擊處理程序作爲參數傳遞。 – user2952238
我相信我的代碼可以滿足你的要求。讓我知道你是否需要修改。 –
它給了我以下錯誤:TypeError:this。 clickHandler不是一個函數。 – user2952238