We all know how to write a class in traditional languages
such as C#, Java etc. With more trend towards Single Page Applications we are
all moving towards writing JavaScript classes. In this blog I will present my preferential
way of writing a JavaScript class while using Knockout. The approach is generic
enough you can use this with another framework
Here is my typical structure:
define([], function () {
var title = ko.observable();
var vm = {
activate:
activate,
title:
title
};
return vm;
function activate() {
return true;
}
});
There are 4 sections in this structure. Here are the details
of each section
1.
At the top I am using AMD module loaders such as
RequireJS to load all the dependencies. This is like include files.
define([],
function () {
// Your class code
});
2.
Once all the dependencies are loaded. I define
all my private variables.
var title = ko.observable();
3.
This is the most important piece. This section
contains the public properties our javascript class exposes. This like an
interface in C#. Using this we can restrict what the consumer can access our
object.
var vm = {
activate:
activate,
title:
title
};
return vm;
As you see I am allowing consumers to access activate method and the
property title.
4.
In this last section we can define all our
functions (both public and private)
function activate() {
return true;
}
As you see with this structure you can get the feel of a traditional
class in JavaScript.