Batman.js is a MVC framework for building stateful client-side applications. If you understand these concepts, you'll build a better batman.js app!
Model-View-Controller (MVC) is a common way of dividing an app's responsibilities. Batman.js borrows its MVC implementation from Rails and Cocoa. There are three main parts:
Models define the business objects in your application. For examples, the models in a blogging app might be
User. These classes may:
- validate incoming data
- persist data
- be associated to other models in your app
Views connect your app to your users by rendering HTML and binding the page to your app. The "view layer" includes HTML templates but goes beyond that: subclasses of
Batman.View are also used for:
- creating reusable UI components
- handling complex user interactions
- rendering into different parts of the page
Controllers handle route changes. Routes invoke controller actions which may:
- select & prepare data
- render views on the page
- persist changes made by the user (eg, clicking "Save")
A critical concern of a single-page app is state, which refers to the information in a program's memory at a given time. Here are a few considerations for state in batman.js:
Storage is asynchronous. Especially if you're using JSON for persistence, loading & saving will be asynchronous. You should set up your app to use callbacks properly (or load some data into your app on page load).
Records "persist" in memory. When you fetch a record from storage, that record will remain in memory until the user leaves the page (or the record is destroyed). If you fetch the record from storage again, the in-memory copy will be updated, but not replaced. Values set on records will stay set between controller actions.
Controllers are singletons. When you first dispatch a controller action, you instantiate that
Batman.Controllersubclass. That same instance will be used to dispatch subsequent actions, so any accessors set on the controller will stay set until you unset them!
Views are objects. When batman.js renders HTML, it is "backed" by a
Batman.Viewinstance. The view object creates state for that HTML by maintaining bindings between the HTML and your app. However, views are destroyed between controller actions (unlike controllers and models).