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 = "";
}
4 Answers 4
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));
}
1 Comment
You can simply:
HTML
<input type="button" onclick="getItems('Names', 'namesDiv'); return false;" value="Go"/>
JS
function getItems(name, div) {
loadingMsg();
GetMsg(name, null, function(r, args) { callback(div, r, args); });
}
EDIT: I think I've covered everything...
Comments
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.
5 Comments
"Names" and "namesDiv" outside of getItems.use addEventListener instead of inline onclick
<input type="button" id="getItems" value="Go" />
JS:
function getItems(name, id) {
loadingMsg(id);
GetMsg(name, null, callback(id));
}
function callback(id){
return (function() {
function(result, args){
clearContainer(id);
//do stuff
document.getElementById(id).append(foo);
}
})();
}
function loadingMsg(id){
clearContainer(id);
// do stuff
document.getElementById(id).append(foo);
}
function clearContainer(id){
document.getElementById(id).innerHTML = "";
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("getItems").addEventListener("click", function() {
getItems("Names", "namesDiv");
}, false);
}, false);