当将ruby编译为js时,我收到JS错误Opal.const_get_relative不是函数

时间:2018-11-18 20:16:45

标签: ruby opalrb

我有一个由Opal转换为JS的Ruby函数,该函数一直可以正常工作,但是突然间它不再起作用。 JS控制台向我显示此错误消息

Opal.const_get_relative is not a function

原始的Ruby代码是这个

Document.ready? do
  Element.find('#button_id').on :click do

翻译成什么

  return $send(Opal.const_get_relative($nesting, 'Document'), 'ready?', [], (TMP_1 = function(){var self = TMP_1.$$s || this, TMP_2;

  return $send(Opal.const_get_relative($nesting, 'Element').$find("#button_id"), 'on', ["click"], (TMP_2 = function(){var self = TMP_2.$$s || this, TMP_3, postcode_value = nil, blokouderling = nil, content = nil, wijk = nil, naam = nil, email = nil, $writer = nil;

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

将Opal应用程序编译为Rails外部文件的最简单方法是使用Opal::Builder构建JavaScript文件,这是一个同时使用Opal和jQuery的简单示例:

gem 'opal', '~> 0.11.4'
gem 'opal-jquery', '~> 0.4.3'

require 'opal'
require 'opal-jquery'

app_html = <<-HTML
  <html><head>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="app.js"></script>
  </head><body></body></html>
HTML

app_code = <<-RUBY
  Document.ready? do
    alert('hello world!')
  end
RUBY

builder = Opal::Builder.new
builder.build('opal')
builder.build('opal-jquery')
builder.build_str app_code, 'app.rb'

File.write 'app.js', builder.to_s
File.write 'app.html', app_html

这时,您只需使用浏览器打开app.html即可看到警报中弹出的“ hello world”消息。