Thursday, April 5, 2012

Using Raphael.js and Backbone.js together

I'm a big fan of Backbone.js. It's lightweight enough to throw into any webapp I'm building, large or small. At the very least it gives me some guidelines on how to organize my code. In larger apps the synchronization with the backend makes my life a lot easier.

An app I'm currently working on makes heavy use of Raphael.js, a great SVG library. In order to unify my handling of user events, I extended the Backbone.js library a little. It's a simple change, but I really like what it did to the organization of code.



As you can see, my goal was to be able to address user interaction with Raphael object in the way I can address interaction with the DOM. DOM events can be specified under events via a "<selector> <event>" syntax, so one can do ".button click" or "#myElement customEvent". Since Raphael abstracts out the DOM from the SVG objects, I wanted to preserve the Raphael events but be able to throw them in with DOM events. So the delegateRaphaelEvents method converts Raphael events to DOM events in the form "raphael:<object name>:<event>".  The assigned callback function gets passed two objects, a jquery event object and a raphael event object.

It works great and keeps my code well organized.  Enjoy!

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hey Peter, I"m just learning Backbone and my first project is using Raphael. You have a RaphaelView somewhere else? I'm just curious to see the full structure of what you're doing here, and how this code works with the rest of your project.

    ReplyDelete
    Replies
    1. I threw the proof of concept I built with this on github: https://github.com/hamiltop/RaphaelBackboneDemo

      You can see the backbone code in apps/assets/javascript/backbone

      You can see it in action at: http://deep-galaxy-3244.herokuapp.com/

      It's crude and pretty ugly, but functional and shows how to use a RaphaelView

      Delete
    2. Thanks Peter! Very cool. Now I just have to decipher your CoffeeScript.

      Delete