Rookie question: I have the following JavaScript functions. This works correctly but I don't want to hardcode the strings "Names" and "namesDiv". I want to pass them in as parameters to the getItems().How do I do this?
Edit: The function GetMsg() returns a JSON object: result.
HTML:
<input type="button" onclick="getItems(); return false;" value="Go"/>
JS:
function getItems() {
   loadingMsg();
   GetMsg("Names", null, callback);
}
function callback(result, args){
   clearContainer();
   //do stuff
   document.getElementById("namesDiv").append(foo);
}
function loadingMsg(){
    clearContainer();
    // do stuff
    document.getElementById("namesDiv").append(foo);   
}
function clearContainer(){
    document.getElementById("namesDiv").innerHTML = "";
}
                For half of them, it's obvious; you just start passing the parameters to the function:
function loadingMsg(containerID) {
    clearContainer(containerID);
    document.getElementById(itemDiv).append(foo);   
}
function clearContainer(containerID) {
    document.getElementById(containerID).innerHTML = "";
}
callback is a little more complex. We'll turn it into a function returning the callback.
function makeCallback(containerID) {
    function callback(result, args) {
        clearContainer();
        document.getElementById(containerID).append(foo);
    }
    return callback;
}
Now we can call makeCallback to get a callback. We can now write getItems:
function getItems(itemType, containerID) {
   loadingMsg(containerID);
   GetMsg(itemType, null, makeCallback(containerID));
}
                        You can simply:
<input type="button" onclick="getItems('Names', 'namesDiv'); return false;" value="Go"/>
function getItems(name, div) {
    loadingMsg();
    GetMsg(name, null, function(r, args) { callback(div, r, args); });
}
EDIT: I think I've covered everything...
 onclick="getItems('namesDiv', 'Names'); return false;"
and then:
function getItems(param1, param2) {
param1 will be namesDiv and param2 will be Names
This said, I'd recommend you take a look at Unobtrusive JavaScript especially the part that talks about separation of behavior from markup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With