简体   繁体   中英

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/

 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'.

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.

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.

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