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.listener
has a unique value for each class.this.recordId
is different each time, it might bethis.userId
orthis.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?
CodePudding user response:
I appreciate the tips in the comments, they helped quite a lot. This is what I ended up writing:
const generateMessageHandler = (listener, callback) => {
return ({ data, origin }) => {
if (
origin === window.location.origin &&
data.listener === listener &&
data.event === 'rowclick'
) {
callback(data.datarow);
}
};
}
And then calling it with this:
window.addEventListener(
'message',
generateMessageHandler(this.rowClickListenerName, (datarow) => {
this.recordId = datarow;
})
);
I think I had all the pieces to start with, but something was blocking figuring out the final implementation until the commenters started talking about functions returning functions.
CodePudding user response:
You can certainly return function inside a function in JavaScript, but what's the point in your case?
You can just set the handler to an anonymous function calling your function:
window.addEventListener('message', () => yourFunction(arg1, arg2, arg3));