Rails 使用 turbolinks Javascript 仅在页面刷新时正确加载
Rails with turbolinks Javascript loads correctly only on a page refresh
在掌握了 Michael Hartls Rails 教程之后,我现在正在尝试编写我自己的第一个 ROR 5 应用程序。现在,我正在尝试在我的应用程序内的页面上实现 JavaScript。 Javascript 显示 html 内的时间并在表格内显示一个因素(根据时间),该因素在加载时计算给定(食用)碳水化合物量的胰岛素。
这是 Javascript 文件 bolus_rechner.js:
//Standard Data for a 3 Year old child
let dFakTni = 0.5;
let faKtmor = 1.3;
let faKtnoon = 0.8;
let fakTeven = 0.5;
let d = new Date();
let h = d.getHours();
let m = d.getMinutes();
let uhrZeit = function zeit() {
if (h < 10) { h = '0' + h; }
if (m < 10) { m = '0' + m; }
return (h + ":" + m + " Uhr");
}
function time(){
let uHr = document.getElementById("Uhrzeit");
uHr.innerHTML = "Es ist " + uhrZeit() + ".";
}
// Displaying the Timebased carbohydrate Faktor (BE-Faktor) and the actual time inside the form and htmluhrzeit document.addEventListener("turbolinks:load",
function timeFakt() {
time();
let beFaktor = document.getElementById("faktor");
if (h > 20 || h < 6) {
beFaktor.value = dFakTni;
}
else if (h >= 6 && h < 11) {
beFaktor.value = faKtmor;
}
else if (h >= 11 && h < 18) {
beFaktor.value = faKtnoon;
}
else if (h >= 18 && h <= 20) {
beFaktor.value = fakTeven;
}
};
document.addEventListener("turbolinks:load", timeFakt);
// Possibiltiy to change the carbohydrate factor (BE Faktor)
function faktorAendern() {
let beFaktor = document.getElementById("faktor");
if (h > 20 || h < 6) {
dFakTni = beFaktor.value;
}
else if (h >= 6 && h < 11) {
faKtmor = beFaktor.value;
}
else if (h >= 11 && h < 18) {
faKtnoon = beFaktor.value;
}
else if (h >= 18 && h <= 20) {
fakTeven = beFaktor.value;
};
};
// Calculation of the needed insulin for the amount of carbohydrates eaten
function insulinBerechnen() {
let eat = document.getElementById("be").value;
let uLin = document.getElementById("insulin");
let prod1 = (eat * dFakTni).toFixed(2);
let prod2 = (eat * faKtmor).toFixed(2);
let prod3 = (eat * faKtnoon).toFixed(2);
let prod4 = (eat * fakTeven).toFixed(2);
if (h > 20 || h < 6) {
uLin.innerHTML = prod1.toString();
}
else if (h >= 6 && h < 11) {
uLin.innerHTML = prod2.toString();
}
else if (h >= 11 && h < 18) {
uLin.innerHTML = prod3.toString();
}
else if (h >= 18 && h <= 20) {
uLin.innerHTML = prod4.toString();
};
};
这是 HTML:
application.html.erb:
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= render 'layouts/rails_default' %>
<%= render 'layouts/shim' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
<%= render 'layouts/footer' %>
<%= debug(params) if Rails.env.development? %>
</div>
</body>
</html>
bolus.html.erb:
<% provide(:title, "Bolus Rechner") %>
<body>
<h1 class="text-center">My Diabetes Diary</h1>
<h2 class="text-center">Bolus Rechner</h1>
<h4 class="text-center text-muted" id="Uhrzeit"></h4>
<div class="container">
<form>
<div class="form-group row top buffer">
<label for="be" class="offset-sm-4 col-sm-2 col-form-label text-left">gegessene BE</label>
<div class="col-sm-1">
<input type="number" class="form-control" id="be" name="be">
<!--<small id="be-info" class="form-text text-muted">
(Hier können Sie die gegessenen Kohlenhydrate in Broteinheiten eingeben.)
</small>-->
</div>
</div>
<div class="form-group row">
<label for="faktor" class="offset-sm-4 col-sm-2 col-form-label">BE-Faktor</label>
<div class="col-sm-1">
<input type="number" class="form-control" id="faktor" name="faktor" value="">
<!--<small id="faktor" class="form-text text-muted">
(Hier können Sie den aktuellen BE-Faktor ändern, wenn nötig.)
</small>-->
</div>
<div class="col-sm-1">
<button class="btn btn-sm btn-danger" type="button" onclick="faktorAendern()">ändern</button>
</div>
</div>
<div class="row">
<div class= "offset-sm-5 col-sm2 ">
<button type="button" class="btn btn-primary btn-md" onclick="insulinBerechnen()">Insulin berechnen</button>
</div>
</div>
<div class="row top-buffer">
<div class="offset-sm-4 col-sm-4 lead bg-warning">
Sie müssen <strong id="insulin"></strong> U (Insulineinheiten) spritzen
</div>
</div>
</div>
</form>
</body>
<head><%= javascript_include_tag "Bolus_Rechner"%></head>
这是header _header.html.erb:
<header>
<nav class="navbar navbar-toggleable-sm navbar-inverse bg-inverse fixed-top">
<a class="navbar-brand" href="#">My Diabetes Diary</a>
<ul class="navbar-nav navbar-right">
<li class="nav-item">
<%= link_to "Home", root_path, :class => "nav-link" %>
</li>
<li class="nav-item">
<%= link_to "Help", static_pages_help_path, :class => "nav-link"%>
</li>
<li class="nav-item">
<%= link_to "About", static_pages_about_path, :class => "nav-link" %>
</li>
<li class="nav-item">
<%= link_to "Bolus Rechner", static_pages_bolus_path, :class => "nav-link" %>
</li>
</ul>
</nav>
</header>
这是 rails_default 部分 _rails_default.html.erb:
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'%>
<%= render 'layouts/shim' %>
我的问题:
1)
当使用 turbolinks:load 作为事件触发器时,当我刷新页面时一切正常。当我在 header 中按下 "Bolus"-link 时,它第一次正常工作。每次我按下 Bolus Link 时,都会将一个 Zero(0) 添加到 "Uhrzeit" 的内部 html 中,这也是由于我的 zeit() 函数。我知道这是因为 turbolinks 兑现了第一个渲染的 bolus.html,并且每次我按下 link 时都会在已经计算的时间上添加一个额外的零。有谁知道如何防止 turbolinks 这样做。
2) 每次我从我的应用程序加载不同的 page/action 时,时间显示中都会添加一个零 (0)。我如何防止 rails/turbolinks 这样做并确保 bolus_rechner.js 仅在我按 link 到推注路径时加载。
提前感谢您的帮助
我找到了解决方案。 JavaScript(bolus_rechner.js) 是问题所在,特别是分配函数以在全局变量中显示时间。
当使用 turbolinks 时,JS 被缓存在 website/application 的全局命名空间中,并且每次应用程序的另一个站点加载时,由于带有 turbolinks:load 的事件侦听器,脚本都会被执行。函数 zeit() 及其 return 值被分配给 uhrZeit。 uhrZeit() 由 time() 执行,time 由 timefakt() 执行。
let uhrZeit = function zeit() {
if (h < 10) { h = '0' + h; }
if (m < 10) { m = '0' + m; }
return (h + ":" + m + " Uhr");
}
也就是说,第一次执行脚本时,实际时间为8h 7m,时间显示为08:07。下次调用该应用程序的站点时,将 8 和 7 分别与 10 进行比较,但仍然小于 10。然后将另一个零添加到 returned 字符串,依此类推。此外还有许多错误,因为在 bolus.html.erb 以外的站点上,具有相应 ID 的 html 元素不存在,这会导致大量引用和类型错误。
解决方案是消除全局变量并使用辅助函数创建时间并在其他函数中使用它们
新脚本如下所示:
function currentMinutes(){
let date = new Date();
return date.getMinutes();
}
function currentHours(){
let date = new Date();
return date.getHours();
}
function time() {
let hours = currentHours()
let minutes = currentMinutes()
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minutes = '0' + minutes; }
return (hours + ":" + minutes + "Uhr");
}
function showTime(){
let uHr = document.getElementById("Uhrzeit");
//checking if the id exists on the page
if (uHr === null){return}
uHr.innerHTML = "Es ist " + time() + ".";
}
// Displaying the Timebased carbohydrate Faktor (BE-Faktor) and the actual time inside the form and html
function timeFakt() {
showTime();
let hours = currentHours()
let beFactorNight = 0.5;
let beFactorMorning = 1.3;
let beFactorNoon = 0.8;
let beFactorEvening = 0.5;
let beFactor = document.getElementById("faktor");
//checking if the id exists on the page
if (beFactor === null){return}
if (hours > 20 || hours < 6) {
beFactor.value = beFactorNight;
}
else if (hours >= 6 && hours < 11) {
beFactor.value = beFactorMorning;
}
else if (hours >= 11 && hours < 18) {
beFactor.value = beFactorNoon;
}
else if (hours >= 18 && hours <= 20) {
beFactor.value = beFactorEvening;
}
};
document.addEventListener("turbolinks:load", timeFakt);
// Calculation of the needed insulin for the amount of carbohydrates eaten
function insulinBerechnen() {
//Form validation and checking if the ids exist on the page
let eat = document.getElementById("be").value;
if( eat <= 0){
alert("If the carbs you ate are zero or below you don't need any insulin");
return};
let beFaktor = document.getElementById("faktor");
if (beFaktor === null){return};
if( beFaktor.value <= 0){
alert("Enter a Valid factor bigger than 0");
return};
let uLin = document.getElementById("insulin");
//calculating the Insulin according to the time of day
let hours = currentHours()
if (hours > 20 || hours < 6) {
if (beFaktor.value === ""){beFactorNight = 0.5}
else {beFactorNight = beFaktor.value};
uLin.innerHTML = (eat * beFactorNight).toFixed(2).toString();
}
else if (hours >= 6 && hours < 11) {
if (beFaktor.value === ""){beFactorMorning = 1.3}
else {beFactorMorning = beFaktor.value};
uLin.innerHTML = (eat * beFactorMorning).toFixed(2).toString();
}
else if (hours >= 11 && hours < 18) {
if (beFaktor.value === ""){beFactorNoon = 0.8}
else {beFactorNoon = beFaktor.value};
uLin.innerHTML = (eat * beFactorNoon).toFixed(2).toString();
}
else if (hours >= 18 && hours <= 20) {
if (beFaktor.value === ""){beFactorEvening = 0.8}
else {beFactorEvening = beFaktor.value};
uLin.innerHTML = (eat * beFactorEvening).toFixed(2).toString();
};
};
我还添加了一种表单验证来检查 0 及以下的值。
那是一些艰苦的工作,但我从中学到了重要的一课。
也许这个 post 可以帮助其他新手程序员解决他们与 turbolinks 的 Javascript 问题,并更好地理解 JavaScript 如何在 RoR5 应用程序的上下文中工作。
干杯塞巴斯蒂安
在掌握了 Michael Hartls Rails 教程之后,我现在正在尝试编写我自己的第一个 ROR 5 应用程序。现在,我正在尝试在我的应用程序内的页面上实现 JavaScript。 Javascript 显示 html 内的时间并在表格内显示一个因素(根据时间),该因素在加载时计算给定(食用)碳水化合物量的胰岛素。
这是 Javascript 文件 bolus_rechner.js:
//Standard Data for a 3 Year old child
let dFakTni = 0.5;
let faKtmor = 1.3;
let faKtnoon = 0.8;
let fakTeven = 0.5;
let d = new Date();
let h = d.getHours();
let m = d.getMinutes();
let uhrZeit = function zeit() {
if (h < 10) { h = '0' + h; }
if (m < 10) { m = '0' + m; }
return (h + ":" + m + " Uhr");
}
function time(){
let uHr = document.getElementById("Uhrzeit");
uHr.innerHTML = "Es ist " + uhrZeit() + ".";
}
// Displaying the Timebased carbohydrate Faktor (BE-Faktor) and the actual time inside the form and htmluhrzeit document.addEventListener("turbolinks:load",
function timeFakt() {
time();
let beFaktor = document.getElementById("faktor");
if (h > 20 || h < 6) {
beFaktor.value = dFakTni;
}
else if (h >= 6 && h < 11) {
beFaktor.value = faKtmor;
}
else if (h >= 11 && h < 18) {
beFaktor.value = faKtnoon;
}
else if (h >= 18 && h <= 20) {
beFaktor.value = fakTeven;
}
};
document.addEventListener("turbolinks:load", timeFakt);
// Possibiltiy to change the carbohydrate factor (BE Faktor)
function faktorAendern() {
let beFaktor = document.getElementById("faktor");
if (h > 20 || h < 6) {
dFakTni = beFaktor.value;
}
else if (h >= 6 && h < 11) {
faKtmor = beFaktor.value;
}
else if (h >= 11 && h < 18) {
faKtnoon = beFaktor.value;
}
else if (h >= 18 && h <= 20) {
fakTeven = beFaktor.value;
};
};
// Calculation of the needed insulin for the amount of carbohydrates eaten
function insulinBerechnen() {
let eat = document.getElementById("be").value;
let uLin = document.getElementById("insulin");
let prod1 = (eat * dFakTni).toFixed(2);
let prod2 = (eat * faKtmor).toFixed(2);
let prod3 = (eat * faKtnoon).toFixed(2);
let prod4 = (eat * fakTeven).toFixed(2);
if (h > 20 || h < 6) {
uLin.innerHTML = prod1.toString();
}
else if (h >= 6 && h < 11) {
uLin.innerHTML = prod2.toString();
}
else if (h >= 11 && h < 18) {
uLin.innerHTML = prod3.toString();
}
else if (h >= 18 && h <= 20) {
uLin.innerHTML = prod4.toString();
};
};
这是 HTML: application.html.erb:
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= render 'layouts/rails_default' %>
<%= render 'layouts/shim' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
<%= render 'layouts/footer' %>
<%= debug(params) if Rails.env.development? %>
</div>
</body>
</html>
bolus.html.erb:
<% provide(:title, "Bolus Rechner") %>
<body>
<h1 class="text-center">My Diabetes Diary</h1>
<h2 class="text-center">Bolus Rechner</h1>
<h4 class="text-center text-muted" id="Uhrzeit"></h4>
<div class="container">
<form>
<div class="form-group row top buffer">
<label for="be" class="offset-sm-4 col-sm-2 col-form-label text-left">gegessene BE</label>
<div class="col-sm-1">
<input type="number" class="form-control" id="be" name="be">
<!--<small id="be-info" class="form-text text-muted">
(Hier können Sie die gegessenen Kohlenhydrate in Broteinheiten eingeben.)
</small>-->
</div>
</div>
<div class="form-group row">
<label for="faktor" class="offset-sm-4 col-sm-2 col-form-label">BE-Faktor</label>
<div class="col-sm-1">
<input type="number" class="form-control" id="faktor" name="faktor" value="">
<!--<small id="faktor" class="form-text text-muted">
(Hier können Sie den aktuellen BE-Faktor ändern, wenn nötig.)
</small>-->
</div>
<div class="col-sm-1">
<button class="btn btn-sm btn-danger" type="button" onclick="faktorAendern()">ändern</button>
</div>
</div>
<div class="row">
<div class= "offset-sm-5 col-sm2 ">
<button type="button" class="btn btn-primary btn-md" onclick="insulinBerechnen()">Insulin berechnen</button>
</div>
</div>
<div class="row top-buffer">
<div class="offset-sm-4 col-sm-4 lead bg-warning">
Sie müssen <strong id="insulin"></strong> U (Insulineinheiten) spritzen
</div>
</div>
</div>
</form>
</body>
<head><%= javascript_include_tag "Bolus_Rechner"%></head>
这是header _header.html.erb:
<header>
<nav class="navbar navbar-toggleable-sm navbar-inverse bg-inverse fixed-top">
<a class="navbar-brand" href="#">My Diabetes Diary</a>
<ul class="navbar-nav navbar-right">
<li class="nav-item">
<%= link_to "Home", root_path, :class => "nav-link" %>
</li>
<li class="nav-item">
<%= link_to "Help", static_pages_help_path, :class => "nav-link"%>
</li>
<li class="nav-item">
<%= link_to "About", static_pages_about_path, :class => "nav-link" %>
</li>
<li class="nav-item">
<%= link_to "Bolus Rechner", static_pages_bolus_path, :class => "nav-link" %>
</li>
</ul>
</nav>
</header>
这是 rails_default 部分 _rails_default.html.erb:
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'%>
<%= render 'layouts/shim' %>
我的问题:
1)
当使用 turbolinks:load 作为事件触发器时,当我刷新页面时一切正常。当我在 header 中按下 "Bolus"-link 时,它第一次正常工作。每次我按下 Bolus Link 时,都会将一个 Zero(0) 添加到 "Uhrzeit" 的内部 html 中,这也是由于我的 zeit() 函数。我知道这是因为 turbolinks 兑现了第一个渲染的 bolus.html,并且每次我按下 link 时都会在已经计算的时间上添加一个额外的零。有谁知道如何防止 turbolinks 这样做。
2) 每次我从我的应用程序加载不同的 page/action 时,时间显示中都会添加一个零 (0)。我如何防止 rails/turbolinks 这样做并确保 bolus_rechner.js 仅在我按 link 到推注路径时加载。
提前感谢您的帮助
我找到了解决方案。 JavaScript(bolus_rechner.js) 是问题所在,特别是分配函数以在全局变量中显示时间。 当使用 turbolinks 时,JS 被缓存在 website/application 的全局命名空间中,并且每次应用程序的另一个站点加载时,由于带有 turbolinks:load 的事件侦听器,脚本都会被执行。函数 zeit() 及其 return 值被分配给 uhrZeit。 uhrZeit() 由 time() 执行,time 由 timefakt() 执行。
let uhrZeit = function zeit() {
if (h < 10) { h = '0' + h; }
if (m < 10) { m = '0' + m; }
return (h + ":" + m + " Uhr");
}
也就是说,第一次执行脚本时,实际时间为8h 7m,时间显示为08:07。下次调用该应用程序的站点时,将 8 和 7 分别与 10 进行比较,但仍然小于 10。然后将另一个零添加到 returned 字符串,依此类推。此外还有许多错误,因为在 bolus.html.erb 以外的站点上,具有相应 ID 的 html 元素不存在,这会导致大量引用和类型错误。
解决方案是消除全局变量并使用辅助函数创建时间并在其他函数中使用它们
新脚本如下所示:
function currentMinutes(){
let date = new Date();
return date.getMinutes();
}
function currentHours(){
let date = new Date();
return date.getHours();
}
function time() {
let hours = currentHours()
let minutes = currentMinutes()
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minutes = '0' + minutes; }
return (hours + ":" + minutes + "Uhr");
}
function showTime(){
let uHr = document.getElementById("Uhrzeit");
//checking if the id exists on the page
if (uHr === null){return}
uHr.innerHTML = "Es ist " + time() + ".";
}
// Displaying the Timebased carbohydrate Faktor (BE-Faktor) and the actual time inside the form and html
function timeFakt() {
showTime();
let hours = currentHours()
let beFactorNight = 0.5;
let beFactorMorning = 1.3;
let beFactorNoon = 0.8;
let beFactorEvening = 0.5;
let beFactor = document.getElementById("faktor");
//checking if the id exists on the page
if (beFactor === null){return}
if (hours > 20 || hours < 6) {
beFactor.value = beFactorNight;
}
else if (hours >= 6 && hours < 11) {
beFactor.value = beFactorMorning;
}
else if (hours >= 11 && hours < 18) {
beFactor.value = beFactorNoon;
}
else if (hours >= 18 && hours <= 20) {
beFactor.value = beFactorEvening;
}
};
document.addEventListener("turbolinks:load", timeFakt);
// Calculation of the needed insulin for the amount of carbohydrates eaten
function insulinBerechnen() {
//Form validation and checking if the ids exist on the page
let eat = document.getElementById("be").value;
if( eat <= 0){
alert("If the carbs you ate are zero or below you don't need any insulin");
return};
let beFaktor = document.getElementById("faktor");
if (beFaktor === null){return};
if( beFaktor.value <= 0){
alert("Enter a Valid factor bigger than 0");
return};
let uLin = document.getElementById("insulin");
//calculating the Insulin according to the time of day
let hours = currentHours()
if (hours > 20 || hours < 6) {
if (beFaktor.value === ""){beFactorNight = 0.5}
else {beFactorNight = beFaktor.value};
uLin.innerHTML = (eat * beFactorNight).toFixed(2).toString();
}
else if (hours >= 6 && hours < 11) {
if (beFaktor.value === ""){beFactorMorning = 1.3}
else {beFactorMorning = beFaktor.value};
uLin.innerHTML = (eat * beFactorMorning).toFixed(2).toString();
}
else if (hours >= 11 && hours < 18) {
if (beFaktor.value === ""){beFactorNoon = 0.8}
else {beFactorNoon = beFaktor.value};
uLin.innerHTML = (eat * beFactorNoon).toFixed(2).toString();
}
else if (hours >= 18 && hours <= 20) {
if (beFaktor.value === ""){beFactorEvening = 0.8}
else {beFactorEvening = beFaktor.value};
uLin.innerHTML = (eat * beFactorEvening).toFixed(2).toString();
};
};
我还添加了一种表单验证来检查 0 及以下的值。
那是一些艰苦的工作,但我从中学到了重要的一课。
也许这个 post 可以帮助其他新手程序员解决他们与 turbolinks 的 Javascript 问题,并更好地理解 JavaScript 如何在 RoR5 应用程序的上下文中工作。
干杯塞巴斯蒂安