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

前端 未结 19 1567
忘了有多久
忘了有多久 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:53

    Recently I found the most clean and easy to understand way of dealing with it:

    $(document).on 'ready page:load', ->
      # Actions to do
    

    OR

    $(document).on('ready page:load', function () {
      // Actions to do
    });
    

    EDIT
    If you have delegated events bound to the document, make sure you attach them outside of the ready function, otherwise they will get rebound on every page:load event (causing the same functions to be run multiple times). For example, if you have any calls like this:

    $(document).on 'ready page:load', ->
      ...
      $(document).on 'click', '.button', ->
        ...
      ...
    

    Take them out of the ready function, like this:

    $(document).on 'ready page:load', ->
      ...
      ...
    
    $(document).on 'click', '.button', ->
      ...
    

    Delegated events bound to the document do not need to be bound on the ready event.

提交回复
热议问题