Ronan
Ronan

Reputation: 177

Use a function with parameters inside a callback

I've written a function which may take an unknown number of functions as parameters, but can't figure how I can make this work when one or more of the functions take parameters too.

Here is a quick example of what I would like to achieve:

function talk(name) {
  console.log('My name is ' + name);
  var callbacks = [].slice.call(arguments, 1);
  callbacks.forEach(function(callback) {
    callback();
  });
}

function hello() {
  console.log('Hello guys');
}

function weather(meteo) {
  console.log('The weather is ' + meteo);
}

function goodbye() {
  console.log('Goodbye');
}

// I would like to be able to do the following:
//talk('John', hello, weather('sunny'), goodbye);

Upvotes: 4

Views: 54

Answers (2)

Dal Hundal
Dal Hundal

Reputation: 3324

talk('John', hello, weather.bind(null, 'sunny'), goodbye);

In this case .bind is essentially returning a function with some bound parameters - quite analogous to Arun's answer, though you may consider this method a little more succinct / readable.

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

You can pass an anonymous function which can call the function with required parameters

talk('John', hello, function(){
    weather('sunny')
}, goodbye);

function talk(name) {
  console.log('My name is ' + name);
  var callbacks = [].slice.call(arguments, 1);
  callbacks.forEach(function(callback) {
    callback();
  });
}

function hello() {
  console.log('Hello guys');
}

function weather(meteo) {
  console.log('The weather is ' + meteo);
}

function goodbye() {
  console.log('Goodbye');
}

talk('John', hello, function() {
  weather('sunny')
}, goodbye);

Upvotes: 8

Related Questions