I'm having trouble working my code as I try to break it into smaller methods due to the link this. My code is as follows:
const pageObject = {
onChange() {
console.log(this);
$('.radio input[type="radio"]').on('click', function() {
console.log(this);
let $id = $(this).data('id');
this.doSomething($id);
}
},
doSomething($id) {
return ...
}
}
pageObject.onChange();
I also want to avoid using esc arrow-functions () =>and self = thismethods, if possible, as recommended in YDKJS: This and Object Prototypes .
Is there a way for a .bind()/.call()/.apply()method onChange()to refer to thiswhich refers to pageObj, as well as to thiswhich refers to the radio?
Feel free to change the code if necessary. Thank you, look forward to!
Update
Thanks event.target, as suggested below, here is a working block of code:
const pageObject = {
onChange() {
console.log(this);
let radioHandler = function radioHandler(event) {
console.log(this);
let $id = $(event.target).data('id');
this.doSomething($id);
}
$('.radio input[type="radio"]').on('click', radioHandler.bind(this));
},
doSomething($id) {
return ...
}
}
pageObject.onChange();
Update 2
this ?, @gyre , ββ , this, , event.target. , MDN Docs Event.target