I have issues getting my code to work as I try to break it down into smaller methods because of the this
referencing. My code is as follow:
const pageObject = {
/* set listener to get id of the radio input and then do something with it*/
onChange() {
// `this` here refers to the pageObject
console.log(this);
$('.radio input[type="radio"]').on('click', function() {
// `this` here refers to the radio input
console.log(this);
let $id = $(this).data('id');
// Error because `this` is referencing the radio input and not the pageObject.
this.doSomething($id);
}
},
/* just does something */
doSomething($id) {
return ...
}
}
// just calls the method on object so we can get started
pageObject.onChange();
I also want to avoid using es6's arrow-functions () =>
and self = this
techniques if possible as recommended in YDKJS: This & Object Prototypes.
Is there a way to .bind()/.call()/.apply()
the method onChange()
to reference the this
which references to the pageObj
and also the this
which references to the radio input?
Feel free to rearrange the code if necessary. Thanks, looking forward!
Update
Thanks to event.target
as suggested below, here is a working code block:
const pageObject = {
/* set listener to get id of the radio input and then do something with it*/
onChange() {
// `this` here refers to the pageObject
console.log(this);
let radioHandler = function radioHandler(event) {
// `this` here also refers to the pageObject too since we are about to call this function via .bind()
console.log(this);
// use event.target here instead. sweet stuff.
let $id = $(event.target).data('id');
// doSomething() now works!
this.doSomething($id);
}
$('.radio input[type="radio"]').on('click', radioHandler.bind(this));
},
/* just does something */
doSomething($id) {
return ...
}
}
// just calls the method on object so we can get started
pageObject.onChange();
Update 2
How to access the correct this
inside a callback? as suggested by @gyre in the comments below provides a great detail of how to control this
but doesn't mention event.target
at all. Anyway, here is MDN Docs on Event.target