[英]why button click not occur in typescript?
您能告訴我為什么打字稿中不會發生按鈕單擊嗎?
這是我的代碼https://jsfiddle.net/z4vo5u5d/238/
class Nav {
private config:object;
constructor(){
this.config = {
$navigationPanel : $('#navigationPanel ul'),
$addItems:$('#adItems')
}
}
init(){
this.attachHandlers();
}
addItems(){
alert('===')
this.config.$navigationPanel.append('<li>tens</li>')
}
attachHandlers(){
this.config.$addItems.on('click' ,this.addItems)
}
}
$(function(){
var n =new Nav();
n.init();
})
當我復制代碼並在此網站上運行http://www.typescriptlang.org/play/
它給出了錯誤
屬性“ $ navigationPanel”在類型“對象”上不存在。
像這樣更新您的attachHandlers
代碼:
這稱為函數原型綁定
attachHandlers(){
this.config.$addItems.on('click' ,this.addItems.bind(this)) /* bind(this) added */
}
注意:-
addItems
是一個事件回調函數,它沒有獲得對Nav
類的引用。 通過結合this
的參考Nav
級而分配Click事件處理addItems
函數獲取訪問Nav
類引用。
綁定事件處理程序時,需要確保這是在addItems方法范圍內的期望值 。 在您當前的迭代中, 它等於config對象 。
要更改this的含義,可以按如下方式使用Function.prototype.bind :
attachHandlers(){
this.config.$addItems.on('click' , this.addItems.bind(this));
}
在這種情況下,我們將類本身作為對此的引用傳遞給函數,因此當觸發處理程序時,它將執行預期的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.