Search code examples
htmlrubyopalrbvoltrb

Appending an element to a page in VoltRb


I'm trying to append an element to one of my pages in a Volt project, via opal-browser, like so:

if RUBY_PLATFORM == 'opal'
  require 'browser'
  $document.body << my_dom_element.to_n
end
# controller code below

Unfortunately, I'm getting an error:

[Error] TypeError: null is not an object (evaluating 'value.nodeType')
    (anonymous function) (main.js, line 7772)

The DOM element that I'm appending is perfectly sound. It's just the following code:

document.createElement( 'myElement' )

I'm assuming that Volt doesn't like me to append elements to a page in a controller, rather than manually creating it in a view HTML file. Is there a way I can work around this? I kind of need to do this element-appending thing for compatibility with another library that I'm using in conjunction with Volt.


Solution

  • Ok, so the problem is that the code you have is being loaded as soon as the compiled .js file loads. You need to run the code once the DOM is ready. The easy way to do this in volt is to run it on a {action}_ready method:

    module Main
      class MainController < Volt::ModelController
        def index_ready
          # run view code here
        end
      end
    end
    

    The index_ready method will be called after the index view has rendered and the dom is ready.