ron
ron

Reputation: 229

Javascript variable function adding extra parameter

So I have a call back function as such

var subscription_callback0 = function(payload) {
                // do something
            };

and another function that will pass an object into the callback function

client.subscribe(dest1, subscription_callback);

The subscribe function above is called from a javascript library which will pass in the payload object when invoked and so the callback function definition is not under my control. But is there anyway that I can pass in an extra argument into the callback function ?

Upvotes: 0

Views: 608

Answers (2)

Rajesh
Rajesh

Reputation: 24945

You should use .bind() to pass parameter to a function while assigning.

Note: This is just a basic implementation of how to pass parameter to function.

You can replace your code to

client.subscribe(dest1, subscription_callback.bind(variableName));

Sample

function notify(str){
  console.log(str);
}

document.getElementById("btn").onclick = notify.bind(null, "clicked button");
<button id="btn">Click Me!</button>

Upvotes: 0

deceze
deceze

Reputation: 522372

Callback function that accepts another argument:

var subscription_callback = function (arg1, payload) {
    // do something
};

Bind the first argument:

client.subscribe(dest1, subscription_callback.bind(null, 'foo'));

Or pass it dynamically:

client.subscribe(dest1, function (payload) {
    subscription_callback('foo', payload);
});

Or closure it when you define the callback in the first place:

var foo = 'bar';

var subscription_callback = function (payload) {
    alert(foo);
    // do something
};

Upvotes: 1

Related Questions