Atomic Object’s blog on everything we find fascinating.

Handling Forms with Marionette.js

Marionette.js is an extension library for Backbone.js that offers many improvements and conveniences to cover common use cases for Backbone. On a recent project, I helped build a large single page application using Marionette.

One thing that Marionette lacks out of the box is a convenient way to manage form lifecycles, including validating and submitting forms with minimal overhead. To address this, I created a generic FormView class that extends Marionette’s ItemView and works with the backbone-validation plugin.

Simplifying Form Handling

This class does a lot of the heavy lifting towards setting up your form for real-time validation. In order to implement a subclass of this, you only need to define 2 functions:

createModel: This function tells your view how to create a model instance after each successful save.

updateModel: This function tells your view how to read data out of your DOM and update the model.

Besides that, it’s just a simple matter of adding Backbone.validation specifiers to you model class and adding data-validation attributes to the correct HTML elements. I’ve included a simple example of a model, view, and template using the FormView below.

While Backbone+Marionette.js is not as full featured as a more comprehensive framework like EmberJS or AngularJS, its simplicity and easiness to understand still makes it one of my favorite Javascript stacks. The code in this post is available on Github. There is also a live demo of the code here.