SVG with Backbone JS

I’m working on an application that allows a user to add and manipulate individual elements on a SVG canvas.  I have used Backbone JS for other projects.   So why not use Backbone to wrap a little structure around this app.

Extending the Backbone View

I’m going to start by creating a Backbone View for the root SVG element.

My HTML looks like this…

When I view and inspect the page, the SVG element is in the body as expected.  However I’m going to have a problem once I try to add anything to that SVG.  Backbone created the SVG element when a new instance of the view was spun up.  This is a great feature of Backbone,  but that element isn’t being created with the SVG namespace.

Looking through the Backbone source I found the function that creates an element if one wasn’t supplied to the view.

This is the line that does the element making.

In my setup, Backbone is using jQuery to create the element.  So all I need to do is change this function to create the element with the proper namespace.  Luckily you can just override this function in the view.

Making it Reusable

I don’t want to override this function in each Backbone View that renders SVG.  Lets create a SVG Backbone View that can be used to extend other views.

Now I can update the SvgCanvas object to extend the new SvgBackboneView object.

Ok, display something already!

Lets create another view with some actual graphics to display as a subview in SvgCanvas.  This view will display a face from my Auto Andy project.

Adding in the Face Subview, the SvgCanvas object now displays a face when rendered.

View Demo on jsFiddle