Royi Namir
Royi Namir

Reputation: 148524

Javascript callback function with parameter?

I have this simple code :

console.log('calling doWork func...')
doWork('a', 'b', myCb);

function doWork(param1, param2, callback)
{
        console.log('in func')
        callback();
}


function myCb(a)
{
        console.log('in callback... for value ' + a)
}

I'm running the function with a callback function -

The output I get is :

"calling doWork func..."
"in func"
"in callback... for value undefined"    // notice the undefined

All ok.

Now, I want the callback to be called with a specified param - something like ( which is incorrect since the () is executing the func) :

doWork('a', 'b', myCb('xxxx'));

I want the output to be :

in callback... for value  xxxx

How do I send a parameter with the myCb call in doWork('a', 'b', myCb);? ( 'when you run the callback function , please run it according to value xxxx')

any help ?

p.s. I want to avoid any global flags solution

thanks.

Upvotes: 2

Views: 4019

Answers (4)

sasikals26
sasikals26

Reputation: 865

console.log('calling doWork func...')
doWork (myCb, "a", "b");
function doWork (callback) {
console.log('in func')
callback (arguments[1], arguments[2]);
}
function myCb (param1, param2) {
console.log('in callback... for value ' + param1)
}

Hope this help you

Upvotes: 0

katspaugh
katspaugh

Reputation: 17899

The common solution is to create another function in place.

doWork('a', 'b', function () {
    myCb('xxxx');
});

You can also use a function that would abstract the currying away. JavaScript (ES5) even has one built-in – Function.prototype.bind. Mind you, the native bind will make your callback slow and has limited support in browsers (see the MDN page).

doWork('a', 'b', myCb.bind(null, 'xxxx'));

Upvotes: 4

Moritz Roessler
Moritz Roessler

Reputation: 8611

Or you could use apply and arguments

console.log('calling doWork func...')
doWork('va', 'b', myCb);

function doWork(param1, param2, callback)
{
        console.log('in func')


        callback.apply(this,arguments);
}


function myCb(a)
{
        console.log('in callback... for value ' + a)
}

JSbin Example

Upvotes: 1

freakish
freakish

Reputation: 56467

One of the solutions is to use .bind:

doWork('a', 'b', myCb.bind(null, 'xxx'));

Upvotes: 1

Related Questions