带有turbolinks的Rails Javascript仅在页面刷新时正确加载

时间:2018-01-08 09:13:51

标签: javascript html ruby-on-rails ruby turbolinks-5

掌握Michael Hartls Rails教程后,我正在尝试编写我自己的第一个ROR 5 Apllication。现在,我正在尝试在我的应用程序内的页面上实现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.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 partial _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时:加载为事件触发器,当我刷新页面时一切正常。当我在标题内按下&#34; Bolus&#34; -link时,它第一次正常工作。每次我按下Bolus Link时,零(0)被添加到&#34; Uhrzeit&#34;的内部。也是因为我的zeit()函数。据我所知,这是因为turbolinks兑换了第一个渲染的bolus.html,每次按下链接时,只会在已计算的时间内增加一个零。有谁知道如何阻止turbolinks这样做。

2)每次从我的应用加载不同的页面/动作时,时间显示都会添加零(0)。如何防止rails / turbolinks这样做,并确保仅在我按下推注路径的链接时才加载bolus_rechner.js。

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 JavaScript(bolus_rechner.js)是问题,特别是指定函数以在全局变量中显示时间。 当使用turbolinks时,JS被缓存在网站/应用程序的全局命名空间中,并且每次应用程序的另一个站点加载脚本时都会执行,因为事件监听器带有turbolinks:load。函数zeit()及其返回值分配给uhrZeit。 uhrZeit()由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。然后将另一个零添加到返回的字符串,依此类推。此外还有很多错误,因为在bolus.html.erb以外的网站上,html元素与各自的ID不存在会导致大量的引用和类型错误。

解决方案是消除全局变量并使用辅助函数创建时间并在其他函数中使用

新脚本如下所示:

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及以下的值。 这是一些艰苦的工作,但我从中学到了一个重要的教训。
也许这篇文章可以帮助其他新手程序员用turbolink解决他们的Javascript问题,并更好地理解JavaScript在RoR5应用程序环境中的工作原理。
干杯塞巴斯蒂安