0

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 ?

1
  • What extra argument? From where to where do you want to pass what? And which part of the code exactly is not under your control? Commented Mar 7, 2016 at 9:15

2 Answers 2

1

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
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I think I like the dynamic solutions you gave me
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.