Batman Batman - 2 months ago 8
jQuery Question

How to pass arguement to named callback in higher order functions

I'm trying to figure out how do I passing in an argument to a named callback function?

For example I have

var result = this.data;

var groupFilter = $("#groupSelect");
var functionFilter = $("#functionSelect");
var skillFilter = $("#skillSelect");

var uniqSkils = _(result).map('skill').uniq().map(populateDropdown(skillFilter));
var uniqFunctions = _(result).map('function').uniq().map(populateDropdown(functionFilter));
var uniqgroups = _(result).map('group').uniq().map(populateDropdown(groupFilter));

function populateDropdown(element) {
element.append($('<option>', {
value: item,
text: item
}))
}


Essentially the result contains dropdown values for three elements. I've created 3 arrays, I've then called uniq for obvious reasons, then I want to go through each array, each item and add it to the correct elements.

But I can't figure out how to pass in the element when using a named callback

Answer

You could have your populateDropdown return a closure that is bound to a particular element:

function populateDropdown(element) {
    return function(item) {
        element.append($('<option>', {
            value: item,
            text: item
        }));
    }
}
Comments