I wanted to run javascript for some particular page. To accomplish this I have created meta tag in layout file like this:
<%= tag :meta, name: :psj, action: action_name, controller: controller_name %>
I have also created a init.js file that will be loaded by application manifest file.
# init.js
var Page, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Page = (function() {
function Page() {
this.action = bind(this.action, this);
this.controller = bind(this.controller, this);
}
Page.prototype.controller = function() {
return $('meta[name=psj]').attr('controller');
};
Page.prototype.action = function() {
return $('meta[name=psj]').attr('action');
};
return Page;
})();
this.page = new Page;
Here is my javascript file for specific controller that need to run on specific action:
# scans.js
$(document).on('turbolinks:load', function() {
if (!(page.controller() === 'scans' && page.action() === 'index')) { return; }
var ajax_call = function() {
$.get("/scans.js", { }, function(table) {
$("#scans").replaceWith(table);
});
}
var interval = 1000 * 60 * 1 ;
setInterval(ajax_call, interval);
});
This works perfect for the scans#index page. Now after visiting this page if I click on any link that loads some other page in same window, ajax_call code runs which should not be the case.
On the contrary if I open that other page in different window it works fine (ajax_call don't run). Is it somehow related to browser's cache or turbolinks cache, not sure what is the cause of the problem.
from Rails: Page specific javascript running on every page if visited in same window
No comments:
Post a Comment