Reputation: 12729
could you please tell me why button click not occur in typescript ?
here is my code 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/
it gives error
Property '$navigationPanel' does not exist on type 'object'.
Upvotes: 1
Views: 117
Reputation: 72269
Update your attachHandlers
code like this:-
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. By binding this
reference of Nav
class while assigning click event handler the addItems
function gets access to Nav
class reference.
Upvotes: 2
Reputation: 3958
When binding the event handler, you need to make sure that this is what you expect it to be within the addItems method scope. In your current iteration, this is equal to the config object.
To change the meaning of this, you can use Function.prototype.bind as follows:
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.
Upvotes: 0