Rails 4: how to use $(document).ready() with turbo-links

前端 未结 19 1569
忘了有多久
忘了有多久 2020-11-21 06:52

I ran into an issue in my Rails 4 app while trying to organize JS files \"the rails way\". They were previously scattered across different views. I organized them into separ

19条回答
  •  情话喂你
    2020-11-21 07:47

    NOTE: See @SDP's answer for a clean, built-in solution

    I fixed it as follows:

    make sure you include application.js before the other app dependent js files get included by changing the include order as follows:

    // in application.js - make sure `require_self` comes before `require_tree .`
    //= require_self
    //= require_tree .
    

    Define a global function that handles the binding in application.js

    // application.js
    window.onLoad = function(callback) {
      // binds ready event and turbolink page:load event
      $(document).ready(callback);
      $(document).on('page:load',callback);
    };
    

    Now you can bind stuff like:

    // in coffee script:
    onLoad ->
      $('a.clickable').click => 
        alert('link clicked!');
    
    // equivalent in javascript:
    onLoad(function() {
      $('a.clickable').click(function() {
        alert('link clicked');
    });
    

提交回复
热议问题