简体   繁体   中英

calling javascript class's method using this keyword in addeventlistener

I want to call the function getItemList() which is in a class 'Example' through addEventListener

var text_box = document.getElementById(this.text_box_id);
text_box.addEventListener('onchange', function(){this.getItemList('3', '10')}, false) 

It should be change , not onchange . Only in IE you have to use on(EventName) .

this inside the handler will refer to text_box (the element the event was raised on). You have to capture a reference to the current this :

var that = this;
text_box.addEventListener('change', function(){    
    that.getItemList('3', '10')
}, false);

Or in browsers supporting bind (you can also provide your own implementation as shown in this documentation):

text_box.addEventListener('change', function(){    
    this.getItemList('3', '10')
}.bind(this), false);

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