[contact-form-7 404 "Not Found"]
Other Ways To Meet Us :info@zealousys.com
Our Blog
Nov 21

Backbone With Coffee in MVC 4

By zealousys


  • Backbone supplies structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling that connects to your existing application over a Restful JSON interface.
  • Backbone provides the reusable building blocks that are required for the majority of applications – following the MVC pattern. MVC is actually a very specific and well-defined pattern composed of Models, Views and Controllers.
  • Backbone is just a small layer built on top of old friends like jQuery which makes it easy to get started building rich client-side features of virtually any size.

Coffee Script

CoffeeScript is a little language that compiles into JavaScript. CoffeeScript doesn’t have all of those embarrassing braces and semicolons that JavaScript has always had. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

In order to demonstrate usage of backbone.js and coffeescript, let us go through a simple example.

1. Configuration Model:
Configuration Model basically contains three configuration properties, i.e. height, width and color of the box. We create ConfigModel class which inherits Backbone.Model class and its ‘initialize’ method (which gets invoked when an instance is created) sets up the default values of the three properties.

  1. Class ConfigModel extends Backbone.Model
  2. initialize: ->
  3. @set ‘color’:’blue’, ‘width’:’100′,’height’:’100′

2. Configuration View:
This view contains two input text boxes which are initialized with default values. This view is responsible for capturing inputs and updating the underlying model. We define two form fields color-input and width-input for taking color and size of the square. Note the identifiers (color-input/width-input) of these two elements and identifier (config-input) of the config container as they will be used coffee script part of the code.

  1. <div id=”config-input” style=”padding: 20px;”>
  2. <div data-role=”fieldcontain”>
  3. <label for=”text”>Enter Color Value (ex. red, green) :</label>
  4. <input id=”color-input” type=”text” value=”blue”></input>
  5. </div>
  6. <div data-role=”fieldcontain”>
  7. <label for=”text”>Enter Width of the box (ex. 50, 70) :</label>
  8. <input id=”width-input” type=”text” value=”100″></input>
  9. </div>
  10. </div>
  11. <ul id=”color-boxes”style=”display: inline; list-style-type:none;”>
  12. </ul>

ConfigInputView class defines the presentation layer of the configuration input and it inherits from Backbone.View class. ‘Initialize’ method creates a linking between the underlying model with this instance of ConfigInputView class. Events field of the class basically binds keyup events on both the input boxes to updateConfig function. updateConfig function simply updates the underlying model’s three properties height, width and color. Note that the thick arrow here “=>” which specifies that updateConfig function should be invoked in context of this instance of ConfigInputView.

  1. Class ConfigInputView extends Backbone.View
  2. initialize: ->
  3. @model.view = @
  4. events:
  5. ‘keyup #color-input’:”updateConfig”
  6. ‘keyup #width-input’:”updateConfig”
  8. updateConfig: (e)=>
  9. @model.set ‘color’ : $(‘#color-input’).val(), ‘width’:$(‘#width-input’).val(), ‘height’:$(‘#width-input’).val()

3. ColorBoxView :
This view is responsible for presenting a single colored box as per the configuration. This view responds to changes on configuration model. Another point to note here is there can be more than one instance of such views and all of them respond to changes in the configuration.

ColorBoxView inherits from Backbone.View. ‘Initialize’ method of the view create a compiled class from a template which is also defined below. We define a method render which simply redraws the content of color box by generating HTML for the containing element from current configuration. We bind render method to be invoked on any change event on the underlying model. The underlying model is config model which gets changed on every keystroke in any of the two input boxes. Render function again defined using thick arrow “=>” makes sure that render function is invoked in context of ColorBoxView instance.

  1. ClassColorBoxView extends Backbone.View
  2. tagName: ‘li’
  3. initialize: ->
  4. @template = $(‘#color-box-template’).template()
  5. @model.bind’change’,@render
  6. @model.view = @
  7. render: =>
  8. $(@el).html$.tmpl@template,@model.toJSON()
  9. Return @

This is the HTML template file that we use for a color box presentation. We are using jquery template library. Two data pieces ${width} and ${color} are filled in the render function to generate the template.

  1. <script type=”text/x-jquery-tmpl” id=”color-box-template”>
  2. <div style=”margin: 20px; float: left;height:${width}px; width: ${width}px; background-color: ${color}; border: 2px solid;”>
  3. </div>
  4. </script>

4. Controller:
Controller is kind of a core which basically binds everything together the above three components. Controller class inherits from Backbone.Controller class and instantiates one instance of ConfigModel, ConfigInputView each and five instances of ColorBoxView. Each of the ColorBoxView gets ConfigModel instance as underlying model.

  1. Class ColorBoxController extends Backbone.Controller
  2. initialize: ->
  3. model = newConfigModel
  4. color_input = newConfigInputView’el’:$(‘#config-input’),’model’:model
  5. forxin[1..5]
  6. view = newColorBoxView{model: model}
  7. $(‘#color-boxes’).append view.render().el

We define a global init method which creates an instance of ColorBoxController and is invoked on documentLoad event of JQuery.

  1. init = ->
  2. cbl = new ColorBoxController
  3. $(document).ready init

What Can We Build for You?


NDA From The Start
We keep your idea safe. We're always willing to sign a Non-Disclosure Agreement with you and fully protect your intellectual property.



For sales inquiry

View My Stats