HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

How to enhance the readability of JavaScript part?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thejavascriptreadabilitypartenhancehow

Problem

There is no doubt that Knockout.js is a very useful tool, which will save you from a lot of JavaScript (jQuery) binding hassle, which will reduce your team's bug ratio concerning this part.

But unfortunately, its JavaScript part gets ugly sooner than you can imagine. The resulting unreadable code is killing me and my team.

Here you can find a simple example from the official website.

This is an official example:

```
var savedLists = [
{ name: "Celebrities", userNames: ['JohnCleese', 'MCHammer', 'StephenFry', 'algore', 'StevenSanderson']},
{ name: "Microsoft people", userNames: ['BillGates', 'shanselman', 'ScottGu']},
{ name: "Tech pundits", userNames: ['Scobleizer', 'LeoLaporte', 'techcrunch', 'BoingBoing', 'timoreilly', 'codinghorror']}
];

var TwitterListModel = function(lists, selectedList) {
this.savedLists = ko.observableArray(lists);
this.editingList = {
name: ko.observable(selectedList),
userNames: ko.observableArray()
};
this.userNameToAdd = ko.observable("");
this.currentTweets = ko.observableArray([])

this.findSavedList = function(name) {
var lists = this.savedLists();
return ko.utils.arrayFirst(lists, function(list) {
return list.name === name;
});
};

this.addUser = function() {
if (this.userNameToAdd() && this.userNameToAddIsValid()) {
this.editingList.userNames.push(this.userNameToAdd());
this.userNameToAdd("");
}
};

this.removeUser = function(userName) {
this.editingList.userNames.remove(userName)
}.bind(this);

this.saveChanges = function() {
var saveAs = prompt("Save as", this.editingList.name());
if (saveAs) {
var dataToSave = this.editingList.userNames().slice(0);
var existingSavedList = this.findSavedList(saveAs);
if (existingSavedList) existingSavedList.userNames = dataToSave; // Overwrite existing list
else this.savedLists.push({
name: saveAs,
userNames: dataToSave
}); // Add new list
this.editingList.

Solution

Quick solution, and not specific to knockout: I'd declare a variable up high in your constructor:

var instance = this;


and replace "this" with "instance" later in the class. You can use a variable name of your choosing, of course, but please bear with me.

My rationale is this thing I experience, as a senior developer, called "code fatigue". Simply stated, it's which "this" is "this"? I do much more c#, where (a) in-scope properties of the current class don't have to be prefixed with "this" and (b) best practice is one class per file -- which can be done in JS, but has to be planned out because of dependency issues.

So, my train of thought is that one of your devs is tasked to do a quick fix on something buggy. Let's He (she) is directed to look at a single function somewhere in a monster Javascript file. Let's say it's a junior developer, to add to the foray. And those "this" references are everywhere. It's INSTANTLY confusing to trace back up to the origin of "this", most especially if the code isn't formatted for viewing. But if you abstract the scope-level "this" into a neat, uniquely NAMED variable, it's a cleaner point of reference and takes the guesswork out.

Just a thought.

Code Snippets

var instance = this;

Context

StackExchange Code Review Q#19900, answer score: 4

Revisions (0)

No revisions yet.