The following is a VERY rough draft of an article I am working on for Alex MacCaw's @maccman's Book. It is very rough, but even now a worthwhile read. Suggestions / comments are very welcome! Please help me :-)

Introduction

JavaScriptMVC (JMVC) is an open-source jQuery-based JavaScript framework. It is nearly a comprehensive (holistic) front-end development framework, packaging utilities for testing, dependency management, documentation, and a host of useful jQuery plugins.

Yet every part of JavaScriptMVC can be used without every other part, making the library lightweight. Its Class, Model, View, and Controller combined are only 7k minified and compressed, yet even they can be used independently. JavaScriptMVC's independence lets you start small and scale to meet the challenges of the most complex applications on the web.

This chapter covers only JavaScriptMVC's $.Class, $.Model, $.View, and $.Controller. The following describes each component:

$.Class - JavaScript based class system

$.Model - traditional model layer

$.View - client side template system

$.Controller - jQuery widget factory

JavaScriptMVC's naming conventions deviate slightly from the traditional Model-View-Controller design pattern. $.Controller is used to create traditional view controls, like pagination buttons and list, as well as traditional controllers, which coordinate between the traditional views and models.

Setup

JavaScriptMVC can be used as a single download that includes the entire framework. But since this chapter covers only the MVC parts, go to the download builder, check Controller, Model, and View's EJS templates and click download.

The download will come with minified and unminified versions of jQuery and the plugins you selected. Load these with script tags in your page:

Static Inheritance

Class lets you define inheritable static properties and methods. The following allows us to retrieve a person instance from the server by calling Person.findOne(ID, success(person) ). Success is called back with an instance of Person, which has the speak method.

Model

JavaScriptMVC's model and its associated plugins provide lots of tools around organizing model data such as validations, associations, lists and more. But the core functionality is centered around service encapsulation, type conversion, and events.

Attributes and Observables

Of absolute importance to a model layer is the ability to get and set properties on the modeled data and listen for changes on a model instance. This is the Observer pattern and lies at the heart of the MVC approach - views listen to changes in the model.

Fortunately, JavaScriptMVC makes it easy to make any data observable. A great example is pagination. It's very common that multiple pagination controls exist on the page. For example, one control might provide next and previous page buttons. Another control might detail the items the current page is viewing (ex "Showing items 1-20"). All pagination controls need the exact same data:

offset - the index of the first item to display

limit - the number of items to display

count - the total number of items

We can model this data with JavaScriptMVC's $.Model like:

var paginate = new $.Model({
offset: 0,
limit: 20,
count: 200
});

The paginate variable is now observable. We can pass it to pagination controls that can read from, write to, and listen for property changes. You can read properties like normal or using the model.attr(NAME) method:

If we clicked the next button, we need to increment the offset. Change property values with model.attr(NAME, VALUE). The following moves the offset to the next page:

paginate.attr('offset',20);

When paginate's state is changed by one control, the other controls need to be notified. You can bind to a specific attribute change with model.bind(ATTR, success( ev, newVal ) ) and update the control:

There are a few problems with this plugin. First, if the control is removed from the page, it is not unbinding itself from paginate. We'll address this when we discuss controllers.

Second, the logic protecting a negative offset or offset above the total count is done in the plugin. This logic should be done in the model. To fix this problem, we'll need to add additional constraints to limit what values limit, offset, and count can be. We'll need to create a pagination class.

There are a few ways to make the Paginate model more useful. First, by adding setter methods, we can limit what values count and offset can be set to.

Setters

Settter methods are model prototype methods that are named setNAME. They get called with the val passed to model.attr(NAME, val) and a success and error callback. Typically, the method should return the value that should be set on the model instance or call error with an error message. Success is used for asynchronous setters.

The following paginate model uses setters to prevent negative counts the offset from exceeding the count by adding setCount and setOffset instance methods.

This is getting sexy, but the Paginate model can make it even easier to move to the next and previous page and know if it's possible by adding helper methods.

Helper methods

Helper methods are prototype methods that help set or get useful data on model instances. The following, completed, Paginate model includes a next and prev method that will move to the next and previous page if possible. It also provides a canNext and canPrev method that returns if the instance can move to the next page or not.

Service Encapsulation

We've just seen how $.Model is useful for modeling client side state. However, for most applications, the critical data is on the server, not on the client. The client needs to create, retrieve, update and delete (CRUD) data on the server. Maintaining the duality of data on the client and server is tricky business. $.Model is used to simplify this problem.

$.Model is extremely flexible. It can be made to work with all sorts of services types and data types. This book covers only how $.Model works with the most common and popular type of service and data type: Representational State Transfer (REST) and JSON.

A REST service uses urls and the HTTP verbs POST, GET, PUT, DELETE to create, retrieve, update, and delete data respectively. For example, a tasks service that allowed you to create, retrieve, update and delete tasks might look like:

To update the server, first change the attributes of a model instance with attr. Then call save().

Save takes the same arguments and returns the same deferred as the create task case.

Destroy a task

task.destroy(
success( task, data ),
error( jqXHR)
) -> taskDeferred

Destroys a task on the server. Destroy takes two parameters:

success - a function that gets called if the save is successful. Success gets called with the task instance and the data returned by the server.

error - a function that gets called if there is an error with the request.

Destroy returns a deferred that resolves to the destroyed task.

The Task model has essentially become a contract to our services!

Type Conversion

Did you notice how the server responded with createdAt values as numbers like 1303173531164. This number is actually April 18th, 2011. Instead of getting a number back from task.createdAt, it would be much more useful if it returns a JavaScript date created with new Date(1303173531164). We could do this with a setCreatedAt setter. But, if we have lots of date types, this will quickly get repetitive.

To make this easy, $.Model lets you define the type of an attribute and a converter function for those types. Set the type of attributes on the static attributes object and converter methods on the static convert object.

CRUD Events

Model publishes events when an instance has been created, updated, or destroyed. You can listen to these events globally on the Model or on an individual model instance. Use MODEL.bind(EVENT, callback( ev, instance ) ) to listen for created, updated, or destroyed events.

Lets say we wanted to know when a task is created and add it to the page. After it's been added to the page, we'll listen for updates on that task to make sure we are showing its name correctly. We can do that like: