Liam
Liam

Reputation: 29714

Passing function into another function (with parameters)

I can't quite seem to figure this out.

I have a function where a parameter filter needs to be a function call that accepts an object built within this function:

function bindSlider(time, filter)
{

   var values = {
     min : 8,
     max : 9
   };

   filter(values);
}

I'm now unsure how to call bindSlider, I thought it'd be something like:

bindSlider(time, function(values) {/*do stuff here and accept values built in bind slider*/});

but this fails with the error:

ReferenceError: fliter is not defined


I know I could do:

function filter(values) {

}

bindSlider(time, filter);

but I want to declare filter differently for each call so a function() {} type pattern is what I'm after.

Upvotes: 0

Views: 60

Answers (2)

Andy
Andy

Reputation: 63524

If you update your code so that the object is properly formatted, you might get rid of the error. Oh, and make sure you're correctly passing in time to the bindSlider function.

var values = {
  min: 8,
  max: 9
};

So:

function bindSlider(time, filter) {

 var values = {
   min: 8,
   max: 9
 };

 filter(values);

}

bindSlider(1000, function (values) {
  console.log(values); // { min: 8, max: 9 }
});

Fiddle.

Upvotes: 0

casraf
casraf

Reputation: 21694

From what I've tested, it does work. Only problem I had was your object used = instead of :. Example:

function bindSlider(time, filter) {
   var values = {
       min: 8,
       max: 9
   };
   filter(values);
}

bindSlider(10, function(values) {
   var html;
   for (var i in values) {
       html = document.getElementById('test').innerHTML;
       document.getElementById('test').innerHTML = html + '<br />' + values[i];
   }
});

JSFiddle

Upvotes: 1

Related Questions