I am writing a JavaScript/HTML driven web application. For the user interface, I am not completely sure that my JavaScript is 'OK'. Mainly, I switch between "modes" by assigning a placeholder variable to a new function, which changes what the onclick event does for items in a table (either open, edit, or move them).
Am I breaking any code styles? Is my script hard to follow or understand? Is it unconventional for me to assign bookmarkEventMapping
to another function later on in my code, using it as a placeholder? What can I do differently? Can you recommend any material that I could read to write clearer JavaScript?
(Please note that this is a WIP)
var bookmarkEventMapping = function() {};//placeholder
/*
...
more JavaScript, which creates <li> elements
that all have onclick events, example:
element.addEventListener(
"click",
function(e) { bookmarkEventMapping(e); }
);
...
*/
function initModeMenu() {//called in <body> onload event
var modeNames = ["normal","edit","move"];//the order in HTML menu
for(var i = 0; i < 3; i++) {,<!-- note: escaped < in loop -->
var node = document.getElementById("modeMenu").children[i];
bookmarkActions[ modeNames[i] ].node = node;
node.dataset["action"] = modeNames[i];
node.addEventListener(
"click",
function() {
bookmarkActions.setCurrentMode( this.dataset["action"] );
}
);
}
bookmarkActions.setCurrentMode("normal");
}
var bookmarkActions = {
"currentMode":"normal",
"setCurrentMode":function(modeName) {
var prevMode = bookmarkActions.currentMode;
bookmarkActions[ prevMode ].exitMode();
bookmarkActions[ prevMode ].node.classList.remove("selected");
bookmarkEventMapping = bookmarkActions[ modeName ].eventMapping;
bookmarkActions[ modeName ].node.classList.add("selected");
bookmarkActions.currentMode = modeName;
},
"normal":{
"initMode":function() {
},
"exitMode":function() {
},
"eventMapping":function(ev) {
}
},
"edit":{
"initMode":function() {
},
"exitMode":function() {
},
"eventMapping":function(ev) {
if(ev.type == "click")
{
bookmarkActions.edit.selectBookmark( ev.target );
}
},
"selectBookmark":function(itemNode) {
itemNode.dataset['bookmarkItemId'];
itemNode.classList.add("editing");//.remove later
}
},
"move":{
"initMode":function() {
},
"exitMode":function() {
},
"eventMapping":function(ev) {
}
}
};
Below is a relevant snippet of HTML from the <body>
<menu id="modeMenu">
<li>Normal</li>
<li>Edit</li>
<li>Move</li>
</menu>