2016-03-24 2 views
0

На самом деле, у меня возникли проблемы с добавлением кода javascript в мое приложение rails.Добавить javascript-код в приложение rails

Я попытался поставить import.js в «app/assets/javascripts», а также не работал.

Я также добавил, // = требует импорта в конце файла application.js, но все еще не работает. В результате все приложение застряло.

index.html.erb

<a href="#">TEST</a> 

<div id = "test"> 

    <h2>Import Statements</h2> 

    <%= form_tag import_samples_path, multipart: true do %> 
    <%= file_field_tag :file %> 
    <%= submit_tag "Import" %> 
    <% end %> 

</div> 

sample.coffee

# Place all the behaviors and hooks related to the matching controller here. 
# All this logic will automatically be available in application.js. 
# You can use CoffeeScript in this file: http://coffeescript.org/ 

    $(document).ready(function() { 
     $("div#test").hide(); 
     $("a").click(function(event) { 
      event.preventDefault(); 
      $("div#test").toggle(); 
     }); 
    }); 

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files 
// listed below. 
// 
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 
// 
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 
// compiled file. 
// 
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 
// about supported directives. 
// 
//= require jquery 
//= require jquery_ujs 
//= require turbolinks 
//= require bootstrap-sprockets 
//= require nicetitle 

Спасибо заранее.

ответ

0

Несколько вещей здесь:

Во-первых - нужно иметь //= require_tree . внутри вашего файла application.js. Для этого автоматически требуются все файлы внутри вашего каталога javascripts.

Далее, (и я не полностью уверен, что это лучшая практика) способ, который я называю JavaScript внутри html.erb файла внутри <script> тега. Я приведу пример моего кода ниже. Я только совсем недавно выяснил, как вызвать JS из html в рельсах, так что я сказал, что это, вероятно, не лучшая практика, но я так и сделал.

<script language="javascript" type="text/javascript"> 
     var counts = ['Count'] 
     var dates = ['x'] 
     <% @chart.datasource.datapoints.each do |c| %> 
      dates.push("<%= c.date %>") 
      counts.push(<%= c.count %>) 
     <% end %> 
     chart(counts, dates); 
</script> 

Таким образом, я фактически положил его внутри тега сценария, как вы видели. Надеюсь, это поможет.

+0

спасибо. Да, он работает. Что делать, если я хочу использовать в application.html.erb для большинства просмотров? –

Смежные вопросы