Exploring JavaScript MV* Frameworks Part 1 – Hello Backbonejs

Javascript-MVC-JuggleJavaScript has become one of the most popular programming languages on the web. At first, developers didn’t take it seriously, simply because it was not intended for server side programming. It was a common misconception among professional developers that this language was meant for “Amateurs” as it focused only on User Interface. JavaScript got the spotlight when the usage of Ajax came to light and professional programmers gave importance to the responsiveness of the page. But now the language has become more popular than ever as the User Experience has become the key part of web development. Accessing web is not limited to browsers alone – there are lot many devices with varying screen sizes accessing the same content. With the rise of HTML5 and CSS3 the web will become more adaptive and responsive than ever and JavaScript plays a major role in it. It has also gained popularity in the server side programming which is made possible by NodeJS framework.

Increase in usage of JavaScript in modern applications demand developers to write maintainable code, separate concerns and improve testability. JavaScript is a “class” less language and it was not designed to support Object Oriented Programming, however you can achieve similar results by workarounds. So if you are a developer from an Object Oriented Programming world, then you will find it hard until you get used to it. Though there are some DOM manipulation libraries like jQuery which simplifies client side scripting of HTML, they actually do not solve the problem of effectively handling separation of concerns. You will end up writing lot many jQuery selectors and callbacks to keep the data in sync between the HTML, JavaScript and the data fetched from the server and we’re still stuck with the Spaghetti code.

Fortunately there are a few libraries and frameworks that come to rescue. Let’s explore few concepts and libraries that assist in structuring JavaScript applications!

This post is the first part of a blog series on JavaScript Frameworks and Libraries out there and I will be exploring BackboneJS here. Stay tuned for others!

What is MV*?

Though all the frameworks out there somewhat tries to be MVC but they do not necessarily follow the pattern strictly. The idea of all the patterns is to separate Model, View and Logic that hooks the two behind which is the controller. However BackboneJS embeds the controller logic in the view itself though it efficiently maintains the separation. On the other side we do have other libraries which implement Model-View-Presenter(MVP) and Model-View-ViewModel(MVVM) pattern. For this reason we will refer these frameworks as MV* implementation.

What is MVC?

Model – View – Controller is an architectural pattern that has been around for a long time and is widely used in server side programming. There are a few frameworks like ASP.net MVC, Ruby on Rails etc. which help web developers to easily program them.

Model – refers to application data and business rules. (a.k.a domain model, entities)

View – what user sees! (HTML page in the web browser)

Controller – mediator between the two. Manipulates the model based on the user interaction. It handles all the logic.

MVC-Process

Image Source: Wikipedia

MVC in JavaScript?

Building single-page applications using JavaScript are getting popular these days and good examples of them are GMail and Google Docs. When you set out to build these type of applications you will most likely invent many of the pieces that make up an MV* coding paradigm. So instead you can make use of some of the famous libraries such as BackboneJS, KnockoutJS, AngularJS, EmberJS .... Let’s explore these frameworks in detail starting with BackboneJS.  

Framework or just a Library?

Before you pick to work on a particular JavaScript Framework or a Library, it’s important to understand the difference between the two. Libraries just fit into your existing architecture and add a specific functionality whereas a Framework gives you an architecture and you will need to follow the rules. To make it simpler for you – Backbone and Knockout are JavaScript libraries and Ember and AngularJS are frameworks. As we explore them you will see the clear difference.

Hello Backbone

Backbone_logo_horizontal

Backbone is a lightweight JavaScript library created by Jeremy Ashkenas who is also known for CoffeeScript. It is designed for supporting Single page web application and has a dependency on UnderscoreJS library which provides utility functions for common JavaScript tasks.

With Backbone, data is represented as Models, which can be created, validated, and saved to the server. Views display the model's state and it re-renders itself when a change is triggered(via a "change" event) in the model due to an UI interaction. This way Backbone provides a structured approach of keeping the data in sync with the HTML UI.

Some of the major websites that used Backbone include USA Today, LinkedIn Mobile, Hulu, WordPress, Foursquare, Bitbucket, Khan Academy and more..

Getting started with Backbone

Script Dependency

Backbone has a dependency on UnderscoreJS or Lo-Dash for utility functions and relies on either jQuery or Zepto for DOM manipulations. So make sure you add them to your page.

<script type="text/javascript" src="../common/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../common/lodash.js"></script>
<script type="text/javascript" src="js/backbone.js"></script>

Backbone.Model

$(function(){
      var Person = Backbone.Model.extend({});
      var person = new Person({name: "James", age: 51});
      var name = person.get("name");
      var age = person.get("age");
      console.log(name + ":" + age);
});

To create a Model class of your own, you extend Backbone.Model and pass a JavaScript object to the constructor and set the attributes.  You can then easily retrieve the values from a get function. You can alternatively set the attributes using a set function.

Backbone.View

Set a template first:

<script type="text/template" id="person-template">
    <div class="view">
        <p>Name: <input type="text" value="<%- name%>"/></p>
        <p>Age: <input type="text" value="<%- age%>"/></p>
    </div>
</script>

Set a container for rendering:

<div id="container">Your content will load in a bit..</div>

Define a view in the script:

//define view
var AppView = Backbone.View.extend({
el: '#container',
model: person,
template: _.template($("#person-template").html()),
initialize: function(){this.render();},
render: function(){this.$el.html(this.template(this.model.toJSON()));}
});
// initialize view
new AppView();

Views in Backbone are almost more convention than they are code so you will  have to rely on some JavaScript templating library like Underscore templates or Mustache.js to do a cleaner separation of the UI. In the above example I have used Underscore’s templating solution to achieve the separation. 

Your own custom Views can be created with the help of Backbone.View.extend. There are few basic properties that you must be aware of to set the View.

  • el – DOM element that the view will be rendered on. In this case it is <div> element with the id “container”
  • $el – a cached jQuery (or Zepto) object for the view’s element
  • model  set the model data that was created using Backbone.Model
  • template –  Backbone is agnostic with respect to your preferred method of HTML templating.  In this case Underscore’s template function is used to set the template that is defined in the “person-template”
  • initialize – this function will be called by Backbone at the time of creation of the view
  • render – this function is used to render the element with the view template and the data. In this case we replace the value in the “container” with the templated view that consists of data from the model

As stated in the Backbone’s documentation – the View class can also be thought of as a kind of controller dispatching events that originate from the UI, with the HTML template serving as the true view. This leads to an argument whether or not Backbone follows real MVC principles. However if you don’t learn it as a MVC library and give importance to the way it separates concerns, it should be fine.

Some time ago Backbone did have its own Backbone.Controller, however it was renamed to Router as the naming for this component didn't make sense from the way it was being set to use.

File Size, Download & Other useful links

File Size: 6.3Kb – minified and 56kb with Full Source and comments.

Download: Backbone website

Annotated Source: http://backbonejs.org/docs/backbone.html

CDN: cdnjs, jsdelivr

Who is using it?: Check out their examples section

Stay Tuned

So that was a quick introduction to BackboneJS and an explanation on JavaScript frameworks in general. In upcoming posts you will be introduced to Ember, Knockout and Angular as well. So stay tuned!

If you have any questions write to me nish@infragistics.com or find me on twitter @nishanil

 

IgniteUI_Banner_300x250_a2


Comments  (7 )

[Infragistics] Tom Puglisi
on Mon, Apr 1 2013 1:39 PM

Great article, thanks!

Nishanth Anil
on Tue, Apr 2 2013 12:55 AM

Thanks Tom!

KESHAV PRAKASH
on Tue, Apr 2 2013 5:51 AM

Nice & very useful article!

Brent Schooley
on Wed, Apr 3 2013 4:38 PM

Oh no Nishanth, I was working on something like this too... ack!  Guess I'll shift gears, awesome post!

Nishanth Anil
on Thu, Apr 4 2013 8:17 AM

Oh :)

Akhilesh Deeti
on Wed, Apr 10 2013 12:54 AM

Hello everybody..! i bugged up solving the infragistics issue in Mozilla latest Version 18.0.2.

i am using Infragistics v11.1.

please get me out of this issue asap .. n u can mail me the answer to akhilesh.d@inteqsolutions.com and mail2akhilesh.d@gmail.com

The issue is :

Input string was not in a correct format

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[FormatException: Input string was not in a correct format.]

  System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +9591147

  System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +119

  System.Convert.ToInt32(String value) +48

  Infragistics.WebUI.UltraWebListbar.UltraWebListbar.getRenderer() +243

  Infragistics.WebUI.UltraWebListbar.UltraWebListbar.get_IsAppStyling() +28

  Infragistics.WebUI.UltraWebListbar.UltraWebListbar.OnPreRender(EventArgs e) +72

  System.Web.UI.Control.PreRenderRecursiveInternal() +103

  System.Web.UI.Control.PreRenderRecursiveInternal() +175

  System.Web.UI.Control.PreRenderRecursiveInternal() +175

  System.Web.UI.Control.PreRenderRecursiveInternal() +175

  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496

Abhishek Narain
on Wed, Apr 17 2013 5:40 AM

JavaScript is client side scripting language used in almost all modern websites and Web applications

Add a Comment

Please Login or Register to add a comment.