[英]why button click not occur in typescript?
could you please tell me why button click not occur in typescript ? 您能告诉我为什么打字稿中不会发生按钮单击吗?
here is my code https://jsfiddle.net/z4vo5u5d/238/ 这是我的代码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();
})
when I copy my code and run on this website http://www.typescriptlang.org/play/ 当我复制代码并在此网站上运行http://www.typescriptlang.org/play/
it gives error 它给出了错误
Property '$navigationPanel' does not exist on type 'object'.
属性“ $ navigationPanel”在类型“对象”上不存在。
Update your attachHandlers
code like this:- 像这样更新您的
attachHandlers
代码:
this is called function prototype binding 这称为函数原型绑定
attachHandlers(){
this.config.$addItems.on('click' ,this.addItems.bind(this)) /* bind(this) added */
}
Note:- 注意:-
addItems
is a event callback function, it doesn't get the this reference to the Nav
class. addItems
是一个事件回调函数,它没有获得对Nav
类的引用。 By binding this
reference of Nav
class while assigning click event handler the addItems
function gets access to Nav
class reference. 通过结合
this
的参考Nav
级而分配Click事件处理addItems
函数获取访问Nav
类引用。
When binding the event handler, you need to make sure that this is what you expect it to be within the addItems method scope. 绑定事件处理程序时,需要确保这是在addItems方法范围内的期望值 。 In your current iteration, this is equal to the config object .
在您当前的迭代中, 它等于config对象 。
To change the meaning of this , you can use Function.prototype.bind as follows: 要更改this的含义,可以按如下方式使用Function.prototype.bind :
attachHandlers(){
this.config.$addItems.on('click' , this.addItems.bind(this));
}
In that context, we're passing the class itself as the reference for this to the function, so when the handler is triggered, it will execute the expected method. 在这种情况下,我们将类本身作为对此的引用传递给函数,因此当触发处理程序时,它将执行预期的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.