简体   繁体   English

Pjax 并在特定页面上重新加载 JavaScript

[英]Pjax and reloading JavaScript on a specific page

I want to implement Pjax and Google Map in my Rails app and I have a problem with the reloading of my JavaScript codes.我想在我的 Rails 应用程序中实现 Pjax 和 Google Map,但我在重新加载 JavaScript 代码时遇到了问题。

My layout/application.html.erb is like this :我的 layout/application.html.erb 是这样的:

<body>
  <%= render 'shared/navbar' %>
  <%= render 'shared/flashes' %>
  <div id="pjax-container">
    <%= yield %>
  </div>
  <%= render 'shared/footer' %>

  <%= javascript_include_tag "https://maps.google.com/maps/api/js?key=******************************" %>
  <%= javascript_include_tag "https://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js" %>

  <%= javascript_include_tag "application" %>

  <%= yield(:after_js) %>
</body>

and the file where is my map listings/index.html.erb is like this :我的地图列表/index.html.erb 所在的文件是这样的:

<div id="map" style="width: 100%; height: 300px;"></div>

<% content_for(:after_js) do %>
  <%= javascript_tag do %>

    $(document).on('ready', function() {
      handler = Gmaps.build('Google');
      handler.buildMap({ internal: { id: 'map' } }, function(){
        markers = handler.addMarkers(<%= raw @markers.to_json %>);
        handler.bounds.extendWith(markers);
        handler.fitMapToBounds();
      });
    })
  <% end %>
<% end %>

@markers is an array of the marker linked to a listing. @markers 是链接到列表的标记数组。 It is defined in the Listings Controller, so it's difficult to move this javascript code.它是在 Listings Controller 中定义的,因此很难移动此 javascript 代码。

The JavaScript code of this file works just when I reload this specific page, and it does not disappear when I change of page.该文件的 JavaScript 代码仅在我重新加载此特定页面时起作用,并且在我更改页面时它不会消失。

So my question is : Is it possible to call a JavaScript code, containing some ruby information, on a specific page with the Pjax system ?所以我的问题是:是否可以使用 Pjax 系统在特定页面上调用包含一些 ruby​​ 信息的 JavaScript 代码?

只需在 pjax 的成功函数中加载您的 javascript。

okay i will explain more about the solution.好的,我将解释更多有关解决方案的信息。 :) :)

in PJAX, most of the time it doesn't load the Jquery or js which is included to the outside of the pjax funciton but in same.在 PJAX 中,大部分时间它不会加载包含在 pjax 函数外部但相同的 Jquery 或 js。 so we have to load that js file in the success funciton of the pjax function using所以我们必须使用 pjax 函数的成功函数加载该 js 文件

$getScript('Your js fle'); $getScript('你的js文件');

so that when pjax fetch new page content then the plugin also loaded and included.这样当 pjax 获取新的页面内容时,插件也会加载并包含在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM