JavaScriptMVC - Model View Controller for JavaScript

You may have heard about the JavaScriptMVC library (it received quite a bit of press because of it's compression capabilities) and may have thought about using it, but haven't played with it yet. Well, I've been looking at the library and have found a few tutorials very useful.

If you haven't downloaded the library you will want to do it before starting working on the tutorials (You can download the library here).

The first tutorial you should read is the getting started tutorial. This tutorial covers the basics of including the JavaScript files and the plug-in files.

Below is an excerpt from the getting started tutorial.

Including plugins and JavaScripts

All JavaScriptMVC functionality comes in the form of a plugin. We'll include the Controller plugin, which organizes your event handlers.

Replace myapp.html with the following HTML. Note the numbered comments, which are explained after the code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
   <head></head>
   <body>
      <script type='text/javascript' src='jmvc/include.js'></script>
      <script type='text/javascript'> 
         include.plugins('controller'); 
include('myscript');
      </script>
   </body>
</html>
  1. Creates a script tag where we'll include a plugin and a script.
  2. Loads the Controller plugin.
  3. Loads myscript.js, a file we'll create in the next section.

The next tutorial that I would recommend reading is the controller tutorial. The tutorial goes over the syntax that is required to use the controller.

Below is an excerpt from the controller tutorial.

Main Controller

If you want to respond to events like:

  • the page being loaded
  • the page being unloaded
  • the page being resized
  • the page being scrolled

you create a special main controller by naming it 'main'. The main controller listens for events on the window, document, and body.

$MVC.Controller('main',{
  // the window onload event handler
  load: function(){
    alert('page loaded');
  },
  // the window resize event handler
  resize: function(){
    alert('page resized');
  }
});

The next tutorial that I would read is the view tutorial. This tutorial gives an overview of how the view functionality is accomplished including the use of templates.

Below is an excerpt from the view tutorial.

Create a Template

The first step towards cleaner code is separating your presentation markup (HTML) from your application logic (JavaScript). We'll do this by separating our presentation markup into a separate file called a template. Create a file called cleaning.ejs and insert the following code:

<h1><%= title %></h1>
<ul>
    <% for(var i=0; i<supplies.length; i++) { %>

        <li>
            <a href='supplies/<%= supplies[i] %>'>
                <%= supplies[i] %>
            </a>
        </li>

    <% } %>
</ul>

You'll notice everything inside <% %> tags is
executed and everything inside <%= %> tags inserts itself into the returned HTML string.

We need to add JavaScript to control the loading and rendering of the template.
We'll replace the original string concatenation code with the following:

// load the template file, then render it with data
var html = new View({url: 'cleaning.ejs'}).render(data);

Doesn't that feel better? The template code restores HTML to its intended structure and the JavaScript code is short and unambiguous.
The dust is clear, now its time to mop.

It is good to see a library try to bring some form of the Model View Controller design patter to JavaScript. If you use this library for any of your projects I would love to hear about them (as usual you can leave them in the comments or write a blog post about it using your free Ajaxonomy account).

Why on earth would you want to use javascript as an MVC? ridiculous.

If you are writing a large JavaScript application like many modern advanced Ajax applications using something like the JavaScriptMVC library. Having said that, you are correct that it will be overkill in some JavaScript implementations. It is one of those case-by-case items that should be used when it makes sense.

As always thanks for your comment.

Totally understand why you might think implementing a MVC framework in JavaScript is overkill or "ridiculous." But consider writing an application in Adobe Air. You're not only updating the interface based on events, your JavaScript is potentially interacting with client side DB, filesystem or remote web services. In a scenario like this your javascript can become incredibly complex and will almost always benefit from a MVC structured solution.

Why would somebody ask this question? All of my last projects include heavy user action with quite complicated domain rules and real time functionality. Current app is first one, where i had to duplicate domain model in client browser. It means, that same domain objects and rules live in server and also in browser. After certain user actions these models are synchronized via AJAX. Both ways. But i was inventing the weel from beginning :) Next time i try this mvc out certainly. But there is a huge need for js MVC.

thank you for your post.

I am wondering about the relevance of this library.
perhabs you can specify the advantages of this libary over :
-mootools
-prototype
-etc.?

thanx!

Interesting idea / implementation.

I see javascript MVC frameworks gaining popularity in the future. The better, faster & more functional javascript becomes, the less need there may be to have other MVC frameworks such as rails or languages like php, asp, etc.

Another reason... Offline app distrubution. If you've got a rails app or php app that you want to distribute to people offline, you'll have to send out a bulky exe file or worse - have them install the library files which no one wants to do. With a javascript based MVC app, you could just send them your app files, maybe in a zip file or something, have them put it on their computer - and presto it's ready to go!

[...] Original post by David Hurth [...]

Not sure if you are aware that MVC has been incorporated wholly into Joomla 1.5.

Wish to see javascript MVC frameworks gaining popularity in the future. The better, faster & more functional javascript becomes, the less need there may be to have other MVC frameworks such as rails or languages like php, asp, etc.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <div> <blockquote> <object> <embed> <img> <param>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Copy the characters (respecting upper/lower case) from the image.