Search code examples
backbone.jsraphaelrequirejsgraphael

Dynamically created element used for Raphael canvas


I have created a Backbone.js/Require.js application that dynamically loads HTML templates to use as "pages" in the application. This means my main HTML page looks like so.

<head>
  // Necessary CSS and Javascripts here
</head>
<body>
  <div id="container"></div>
</body>

And then I used underscore templates to render new elements dynamically to the DOM. However, a new feature requires the use of a Raphael.js chart. I created a new element <div id='canvas'></div> and call Raphael('canvas') but since the canvas element wasn't there on DOM ready, Raphael can't see the newly created element.

I have attempted to use a jQuery selector in place of the id reference like so Raphael($('#canvas')) but this attaches the canvas to the body element and not my container element.

Any suggestions on how to bind a Raphael canvas to a dynamically created element?


Solution

  • A way to overcome this issue is by creating an empty element in the view and binding everything onto that. I have never worked with Raphael, but I think this could work:

    var someView = Backbone.View.extend({
        el: document.createElement('div'), // This creates a DOM element '<div></div>'
    
        initialize: function(){
            Raphael(this.el); // Attach Raphael, you could also go with jQuery
        },
    
        render: function(){
            jQuery('#container').append(this.el); // Add to DOM somehow
        }
    })