Turbolinks - 仅在预定帖子上显示日期时间选择器 - 默认隐藏

Turbolinks - Showing datetimepicker only on Scheduled posts - hidden by default

我有一个 _form 部分顺序 create/edit posts。此表单有一个用于设置 post 状态的下拉列表,因此如果用户将状态设置为 Scheduled 那么 datetimepicker 会显示以便 select 一个日期,否则应该隐藏它默认情况下(即当状态为 "Draft" 或 "Published" 时)。

# app/views/posts/_form.html.haml
= simple_form_for ["admin", @post] do |f|

  = f.input :title

  = f.input :status, collection: ["Draft", "Published", "Scheduled"], selected: status_for(@post)

  .published-field
    = f.input :published_at, as: :date_time_picker

...

# app/helpers/posts_helper.rb
module PostsHelper
  def status_for(post)
    if post.published_at?
      if post.published_at > Time.zone.now
        "Scheduled"
      else
        "Published"
      end
    else
      "Draft"
    end
  end
end

# app/assets/javascripts/posts.coffee
changeVisibility = (status) ->
  if status == "Scheduled"
    $(".published-field").show()
  else
    $(".published-field").hide()

jQuery ->
  changeVisibility $("#post_status :selected").text()
  $("#post_status").on "change", (e) ->
changeVisibility $(this).find(":selected").text()

当用户第一次访问该页面时出现问题,因此默认情况下 status 设置为 Draft(正如预期的那样),但是 datetimepicker 是可见的,这是不应该的到(记住?这应该只有在用户 select 安排 post 时才可见)。如果此时在查看表单时刷新页面,则日期选择器会消失。

原始问题也可以在这里找到https://gorails.com/episodes/scheduling-posts

这个问题可能是由于 turbolinks 引起的。我也尝试过使用jquery-turbolinks gem,但没能解决问题。有解决此问题的想法吗?

我不擅长咖啡脚本,给你看javascript代码。

var ready = function(){
  changeVisibility ($("#post_status :selected").text());
  $("#post_status").on("change", function(e){
  changeVisibility $(this).find(":selected").text();
 });
}
$document.ready(ready);
$document.on('turbolinks:load',ready);

GemFile 添加此代码

gem 'turbolinks', '~>5' 

如果你想使用 Turbolinks,重要的是要记住它的工作原理是根本没有真正的页面加载,它只是做一个 XHR 请求然后替换 <body> 中的 HTML,而保存旧的 <body> 以实现后退按钮。

这意味着不会执行任何脚本,您不会获得任何文档 load/ready 事件等。$(handler)$.ready(handler) 相同,仅在 运行页面加载一次 "page's Document Object Model (DOM) becomes safe to manipulate.".

Turbolinks 在 document 上触发 turbolinks:load,因此对所有此类事情使用 $(document).on('turbolinks:load', handler)

你还需要知道它保留了你的旧 <body> DOM 和任何脚本的副本,所以它使用的任何内存,以及任何其他 JavaScript 从最后 "page" 如超时和动画帧等保持 运行ning。并且您使用它在加载时基于 CSS 选择器实现了 show/hide。

这个 Rails guide has more information, as well as the Turbolinks 库本身。