I have code like this about five times in my project, and I know I'm going to have it more often than that:
this.messageHandler = ({ data, origin }) => {
if (origin === window.location.origin) {
if (
data.listener === this.listener &&
data.event === 'rowclick'
) {
this.recordId = data.datarow;
}
}
};
window.addEventListener('message', this.messageHandler);
Each time here are the only differences:
this.listenerhas a unique value for each class.this.recordIdis different each time, it might bethis.userIdorthis.accountId, but so far I'm always setting a property that represents a record's ID.
I'd like to create a function that builds this function. I think this is possible in JavaScript. I seem to remember seeing information on how to do it in one of the many JS resources I used when learning the language. But I can't find the information now.
Ideally, I'd replace the above with something like this:
window.addEventListender('message', generateHandler(this.listener, (datarow) => {
this.recordId = datarow;
});
How can I do this in JavaScript?
thisrefers to? Perhaps looking at closures might help but I wasn't sure if that's what you were after.