Problem
I want to make show/hide logic more maintainable in my codebase.
Because they are too faraway located in separate js files, it hard for people to maintain.
The flow in my codebase is:
require.js init (hide the target DOM at first) → app.js → load_comments.js (show the target DOM if the comments length > 0)
main.js (require.js manifest file)
$("#target_dom").hide();
app.js
define([
'load_comments',
"jquery"
],function( comments, $){
return {
initialize: function(){
console.log("app.js initialized");
}
}
})
load_comments.js
var CommentView = Backbone.View.extend({
el: $("#comments_section"),
render: function() {
var notNullComments = comments.wellFormedComments();
if (notNullComments.length > 0) {
$("#target_dom").show();
}
var html = commentsTmpl(notNullComments.toJSON());
$(this.el).append(html);
},
});
Solution
From a once over:
load_comments
should follow lowerCamelCase ->loadComments
- Avoid
console.log
, at least wrap it in something that also takes in to account message severity and filters on that message severity - Personally I would have used either
comments
orwellFormedComments
instead ofnotNullComments
- It seems that if there are no comments, that you should get out, and not do the JSON parsing and the html appending
- Where is
commentsTmpl
defined? Smells like a global variable - It is very confusing to have
#target_dom
there, I am guessing that it is a subelement of#comments_section
, but I would have called it#comments
probably? - Even more confusing is that you append the html to
#comments_section
and not#target_dom
All in all, I would go with something like this:
var CommentView = Backbone.View.extend({
el: $("#comments_section"),
render: function() {
var comments= comments.wellFormedComments();
if (!comments.length) {
return
}
$("#a_descriptive_id").show();
var html = commentsTmpl(notNullComments.toJSON());
$(this.el).append(html);
},
});