Sherwin Flight Sherwin Flight - 1 month ago 16
Javascript Question

Passing variables in a JavaScript callback

I'm having trouble finding some information, and it's almost certainly because I don't know the correct terminology for what I'm doing. When I search for info about variables in a callback function, the code not the same as what I am trying to do here.

I have some JavaScript code, this is part of it:

var myNotification = new Notify('Notification Title', {
body: 'message goes here',
icon: "/icon.png",
tag: 'for app use',
notifyClick: functionNameHere,
timeout: 10
});


The "functionNameHere" part is the name of another function, that is called when the notification created by this script is clicked.

I need to be able to pass a variable along with it, so essentially what i need to do is:

var myNotification = new Notify('Notification Title', {
body: 'message goes here',
icon: "/icon.png",
tag: 'for app use',
notifyClick: functionNameHere('variableContentWouldbeHere'),
timeout: 10
});


However, when I do it like that it doesn't work properly.

How would I achieve this?

Answer

You can achive this with changing function scope or using closures.

1st:

notifyClick: functionNameHere.bind('variableContentWouldbeHere');

And your context inside "functionNameHere" implementation is your argument.

function functionNameHere() {
   console.log(this === 'variableContentWouldbeHere'); //true
}

2nd:

Using closures

notifyClick: function() { functionNameHere('variableContentWouldbeHere'); }