1

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.

GDP2
  • 1,948
  • 2
  • 22
  • 38
  • How are you calling this code? Can you show the full file somewhere? I suspect this is being called before the DOM is ready. – Ryan Jun 23 '15 at 03:16
  • @Ryan Here is the full code of the file in question: https://gist.github.com/ylluminarious/e9c7123c469682dae794#file-gistify248120-rb-L36. Fyi, this is the out-of-the-box `main_controller.rb` file and, as you can see in the gist, the page that I'm attempting to append an element to is the out-of-the-box "About" page. – GDP2 Jun 23 '15 at 03:28

1 Answers1

1

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.

Ryan
  • 956
  • 7
  • 8
  • Shoot, I think I was wrong about where the code is being called. I removed the `$render.call` line and I got the same response, as well as trying the {action}_ready method. I guess the problem must be located somewhere else. – GDP2 Jun 23 '15 at 04:20
  • in the example you gave, its trying to do: $document.body << renderer.dom_element.to_n outside of the $render Proc. The whole thing should be run from a _ready method – Ryan Jun 23 '15 at 06:40
  • Ah, ok. I see what you're saying. I ran the whole thing in a _ready method and it seems to be working fine now. Thanks! :) – GDP2 Jun 23 '15 at 15:45