Create Javascript MVC Framework in Less Than 200 Lines (Part-1)

javascript_mvc_framework

Why ?

It is required to write javascript code in a robust and secure way. If you've a large scale application then you can use popular frameworks like Angular JS, Knockout JS, Backbone JS, etc.

But if you've a small application then you need to write your code in a robust and secure manner. In order to achieve this you can use MVC pattern.

If we want to have a MVC Pattern framework then we need to have following concepts.

What ?

  • Routes and Controllers
  • Factory (for code reusability)
  • Constants
  • Template loading and binding
  • Flexiblie integration of modules

So, let's achieve this step by step.

  1. Know about 'return' keyword in javascript functions.
  2. Concept of class's and objects in javascript
  3. Know about Javascript design patterns.
  4. Architect your framework.
  5. Concept of factories.
  6. Concept of constants.
  7. Concept of Dependancy Injection
  8. Concept of routes and controllers.
  9. Sample app
  10. About "return" keyword

In javascript functions, if you return something from function then it acts as a public item.

Examples:

Returning a value:

function getAValue(){
 var a = 10;
 return a;
}

In function "getAValue" a is a private variable, but you can access it through return that variable.

var new_a = getAValue();
console.log(new_a);

Output:

10

Returning an object with values:

function getAnObject(){
 
 var Obj = {
 'key1':'val1',
 'key2':'val2'
 }
 
 return Obj;
}
var new_obj = getAnObject();
console.log(new_obj);

Output:

{'key1':'val1', 'key2':'val2'}

Returning a function

function getAFunction(){
 
 var func = function(){
 console.log("im a private function");
 }
return func;
}
var new_func = getAFunction();
console.log(new_func);

Output:

function(){
 console.log("im a private function");
 }

Returning an object with functions

function getFunctions(){
    var funcs = {
        'func1': function(){
         console.log("im func1");
    },
     
        'func2': function(){
         console.log("im func2");
    },
}
   return funcs;
}
var new_funcs = getFunctions();
console.log(new_funcs);

Output:

{func1: function(){ console.log("im func1")}, func2: function(){ console.log("im func2") }}
  1. Concept of Objects and Privacy

In JavaScript, there are different ways to create an object. The function is a first-class object. That affords us numerous ways in which to use them that other languages simply cannot. For example we can pass functions as arguments to other functions and/or return them. Functions also play a highly specialized role in Object creation, because objects require a constructor function to create them - either explicitly or implicitly. Another salient feature of the JavaScript language is that it is interpreted at runtime. This is relevant because code can be written and evaluated at runtime.

Objects

JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. So what are objects? Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly.

If a value is a function, we can consider it a method. When a method of an object is invoked, the this variable is set to the object. The method can then access the instance variables through the this variable.

Objects can be produced by constructors, which are functions which initialize objects. Constructors provide the features that classes provide in other languages, including static variables and methods.

Public

The members of an object are all public members. Any function can access, modify, or delete those members, or add new members. There are two main ways of putting members in a new object:

In the constructor

This technique is usually used to initialize public instance variables. The constructor's this variable is used to add members to the object.

function Container(param) {
      this.member = param;
}

So, if we construct a new object

var myContainer = new Container('abc');
then myContainer.member contains 'abc'.

In the prototype

This technique is usually used to add public methods. When a member is sought and it isn't found in the object itself, then it is taken from the object's constructor's prototype member. The prototype mechanism is used for inheritance. It also conserves memory. To add a method to all objects made by a constructor, add a function to the constructor's prototype:

Container.prototype.stamp = function (string) {
    return this.member + string;
}
So, we can invoke the method
myContainer.stamp('def');
which produces 'abcdef'.

Private

Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.

function Container(param) {
     function dec() {
          if (secret > 0) {
              secret -= 1;
              return true;
           } else {
              return false;
           }
     }
    this.member = param;
    var secret = 3;
    var that = this;
}

The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.

Privileged

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Privileged methods are assigned with this within the constructor.

function Container(param) {
      function dec() {
           if (secret > 0) {
               secret -= 1;
               return true;
           } else {
               return false;
          }
      }
     this.member = param;
     var secret = 3;
     var that = this;
     this.service = function () {
             return dec() ? that.member : null;
     };
}

service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null. service calls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

In next part we'll see about design patterns and architecting our framework.

sources: here