Using backbone-forms with CoffeeScript's class syntax

backbone-forms is a really easy way to add forms that come with powerful client-side validation. As I write this there’s an AMD version in the repo to use with require.js and although it’s not perfect you can fish through the pull requests to get something that works well with the Bootstrap templates plugin. Since I’m working in CoffeeScript and using the class-extends syntax I wanted to avoid instantiating new forms in a Marionette application and passing in the schema and template like backbone-forms usually requires and instead treat each form as a view class that has it’s own properties.

In the Gist below I created a new Form class that copies attributes from *this* to the options object and use CoffeeScript’s super method to pass these to backbone-forms’ default initialize method. Especially for a case where a model is involved, perhaps a user’s settings page, this keeps the form schema out of the model and allows you to pass in a model for it’s data alone. I also override the default render method to allow passing in a template directly as text. Since I’m using require-jade for templates this also allows me to easily use a custom form, in one case to add ‘Log In’ and ‘Forgot Password’ buttons below the fields that get rendered.

And that’s it! Now you can have powerful forms treated just like views in your Backbone app.