Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Using Models in Javascript

Monday, January 14th, 2013 by Servage

Working with a MVC framework on the server adds enormous benefits to your project. So why not do it on the client-side as well? Javascript is perfectly capable of being used for object oriented programming, working with data models that can represent entities in the data base, like active record for example.

Backbone.js is a project offering such an interface for your Javascript development. It can automatically handle, sort and use a set of data models, and communicate with a server-side API to perform various actions. “Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.”

Example

The following example shows a little of the power in Backbone.js and how simple the code is structured:

var Sidebar = Backbone.Model.extend({
  promptColor: function() {
    var cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();

Using Backbone.js, you could quickly add rich features to your website with little effort on the data handling.

Using Models in Javascript, 3.0 out of 5 based on 2 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.