In one of the web apps I contribute to, the main.js
file has multiple interacting "objects". Unfortunately, I'm so bad at OOP in JavaScript, despite studying other questions, that I just have a bunch of functions divided by a comment block as follows for the editor "object":
//*****************
// Setup the editor
//*****************
//Functions for interaction with editor
var aceRange = ace.require('ace/range').Range;
var editor = null;
var marker = null;
var gui_updating = false;
function removeMarker() {
if (marker != null) {
editor.getSession().removeMarker(marker);
marker = null;
}
}
function annotateLine(d) { //Called on mouseover in graph
removeMarker();
marker = editor.getSession()
.addMarker(new aceRange(d.line, 0, d.line, 10),
'highlight', 'fullLine', true);
editor.getSession().setAnnotations([{row: d.line, type: 'info'}]);
}
function clearAnnotation(d) { //Called on mouseout in graph
removeMarker();
editor.getSession().clearAnnotations();
}
The initialization of the editor "object" and it's bonding to events is called later, but isn't included here as I don't think it will help.
This seems bad, but I can't figure out how to improve it other than dividing the objects into separate files. I also think it's important to divide the code functionally, but I'm not sure how to do that. Should I wrap the whole thing up in a function?
Like so:
var app_editor = function(ace, ace_editor){
self.aceRange = ace.require('ace/range').Range;
self.editor = ace_editor;
self.marker = null;
removeMarker = function() {
if (self.marker != null) {
self.editor.getSession().removeMarker(self.marker);
self.marker = null;
}
}
annotateLine = function(d) { //Called on mouseover in graph
removeMarker();
self.marker = self.editor.getSession()
.addMarker(new self.aceRange(d.line, 0, d.line, 10),
'highlight', 'fullLine', true);
self.editor.getSession().setAnnotations([{row: d.line, type: 'info'}]);
}
clearAnnotation = function(d) { //Called on mouseout in graph
removeMarker();
self.editor.getSession().clearAnnotations();
}
};
Should I be using prototypes as well, even if there will only be one function ever? I understand what a closure is, but I still don't know how to apply it and if it's appropriate here. Alternatively, since my code has gotten so big, should I look into using a library?
This project is still in its early stages, so I'm open to radical changes.