2014-04-28 66 views
3

頁面特定的JavaScript的正確方法我想包括這一點,例如:在一個Rails應用程序包括在Rails中

jQuery(document).ready(function($) { 
    $('#my-modal').modal(options) 
}); 

在一個特定的地方。在我的情況下,該文件被稱爲views/modals/mymodal.html.erb。那裏,只有那裏。

我不知道如何做到這一點,如果我沒有把它放在所有頁面上,就像我把它放在資產中一樣。謝謝!

回答

1

其中一個解決方案是在插入我們的JavaScript到其自身的文件:Reference Link

例如:

//應用程序/資產/ Java腳本/ alert.js

alert("My example alert box."); 

而且包括此文件僅在我們希望它執行的視圖中:

<%# app/views/page/contact.html.erb %> 
<%= javascript_include_tag "alert" %> 
<h1>Contact</h1> 
<p>This is the contact page</p> 

An d不要忘記在文件列表中選擇您的新文件進行編譯:

# config/environments/production.rb 
config.assets.precompile += %w(alert.js) 
1

由於JS文件要包括名爲my_modal.js

  1. 將您JS文件放置assets/javascriptsassets/javascripts的某個目錄中,例如application

  2. 在您的application.js中更改行//= require_tree .//= require_tree application(它可以防止在每個頁面上加載my_modal.js)。

  3. 將您my_modal.jsassets/javasctripts

  4. 添加my_modal.jsconfig.assets.precompile陣列(config assets.precompile += ['my_modal.js'])在application.rb

  5. javascript_include_tag 'my_modal'在視圖中要包含這個文件

你可以去Rails guides參考。

6

這些都是一些有用的技巧

#1文件JS

  • 具體的佈局
  • 爲JavaScript中創建文件your.js
  • 調用文件your.jsapplication.js
  • 刪除//= require_tree .your.js添加到資產編譯器on config/application.rbconfig.assets.precompile += %w(your.js)

#2投產特定文件非佈局(不推薦)

把你的JS腳本用JavaScript代碼來對mymodal.html.erb


#3使用的if..else。

將您的js腳本放入layout/yourlayout.html.erb並使用if.. else..邏輯。

例如:

<% if current_page?(yourspecific_path) %> 
    <script language="text/javascript"> 
    your javascript here .. 
    </script> 
<% end %> 

瞭解更多關於herecurrent_page?

或者使用request.fullpath來獲取當前的完整路徑

例如:

<% if request.fullpath == yourspecific_path %> 
    <script language="text/javascript"> 
    your javascript here .. 
    </script> 
<% end %> 

更多hererequest.fullpath

也可以結合使用#1和#3,如果你想腳本放入文件.js

歡呼

+0

鏈接不工作... – Rubyist

+0

謝謝,鏈接編輯。 –

+0

+1有一些新東西... – Rubyist

0

晚會晚了,但對於今天任何人來說,我想我已經想出了更好的東西。

Punchbox Gem for Rails

有了這個,你可以編寫代碼,如:(你也可以創建一個對象,而不是一類查看文檔)

class Post { 
    controller() { 
    // Runs on every action 
    } 
    index() { 
    // Runs on just the index action 
    } 
} 

Punchbox.on('Posts', Post); 

我已經寫這更深入這裏:https://kierancodes.com/blog/page-specific-javascript-in-rails-4