I'm currently building some HTML with JS (specifically using the jQuery library). My code is as follows:
goToError: function (error, returnView, returnController, callback) {
console.log(error);
this._transitionOutPanel(function () {
loadError();
});
var loadError = function () {
$("#panel").html("");
navigation.setHeader("Error");
(function buildErrorHtml() {
var ctrlDiv = $('<div></div>', {
style: "text-align: center;"
});
var ctrlP1 = $("<p></p>", {
html: ("An error occured while loading this view.<br><b>Error code:</b> {0} ({1})").format(error.status, error.statusText)
}).appendTo(ctrlDiv);
var ctrlP2 = $("<p></p>").appendTo(ctrlDiv);
var ctrlBackBtn = $("<button></button>", {
html: "Back",
class: "btn btn-danger"
}).appendTo(ctrlP2);
ctrlBackBtn.click(function () {
if (returnView != null && returnController != null) {
navigation.go(returnView, returnController);
} else {
navigation.go("Login", "Accounts", null, "Login");
}
});
ctrlDiv.appendTo("#panel");
})();
navigation._transitionInPanel(function () {
if (typeof callback === "function")
callback.call(this);
});
};
loadError();
}
More specifically, my question is in regards to when it is best to use a comment vs a function expression for code clarity. I currently have a self-invoking function expression named buildErrorHtml()
that constructs the HTML and appends it to the relevant element on my page.
Would this be better outside of a function expression (amongst the rest of the code in var loadError = function() { ... }
) or should it be as it is, inside an anonymous function? I've been told to only use comments to tell readers 'why' instead of 'what', and I don't feel using a comment is justified with this criteria.
The alternative is using a comment like so:
// Build HTML
var ctrlDiv = $('<div></div>', {
style: "text-align: center;"
});
...
Which method tells anybody reading my code what it is the code is doing best?
Feedback on anything else is also greatly welcome.
buildErrorHtml
function name won't really make much of a difference . \$\endgroup\$ – Peter Olson Nov 30 '15 at 2:48