简体   繁体   English

barba js v2 重新初始化 main.js 脚本

[英]barba js v2 reinit main.js script

I am struggling with barba js v2.我正在努力使用 barba js v2。 After ajaxtransition my main.js script stops working. ajaxtransition 后,我的 main.js 脚本停止工作。 I would like to reinit this script somehow...我想以某种方式重新启动这个脚本......

I have simple barba transition like this ->我有这样简单的 barba 过渡->

import barba from "@barba/core"

class Transition {
  constructor() {
    // console.log(barba)
    this.events()
  }

  events() {
    // console.log("events")
    barba.init({
      transitions: [
        {
          name: "default-transition",
          leave() {
            // create your stunning leave animation here
            console.log("leave")
          },
          enter() {
            console.log("enter")
            // create your amazing enter animation here
          }
        }
      ]
    })
  }
}

export default Transition

and at the and of </body> tag I have</body>标签的 and 我有

    <script src="js/main-dist.js"></script>
  </body>

Inside this main-dist.js script there are couple of other scripts that are imported, for example a function that shows current date.在这个 main-dist.js 脚本中,还导入了几个其他脚本,例如显示当前日期的 function。

When I go to the page at first time, everything works fine, but when I go to another page and come back to the page that should display the current date, the date is not displaying because script is not initialized.当我第一次 go 到该页面时,一切正常,但是当我 go 到另一个页面并返回应显示当前日期的页面时,由于脚本未初始化,日期未显示。 It initalizes only on load not on ajaxload.它仅在加载时初始化,而不是在 ajaxload 时初始化。

So my roadblock is to re-init somehow this script on ajaxload.所以我的障碍是在 ajaxload 上以某种方式重新初始化这个脚本。

I figured it out.我想到了。 There is barba hook "after" that we can use in the transition script:)我们可以在转换脚本中使用 barba hook "after" :)

barba.hooks.after(() => {
const bottomDOM = document.getElementsByTagName("body")[0]
const newScript = document.createElement("script")
const oldScript = document.querySelector(".main-script")
newScript.src = "js/main-dist.js"
newScript.className = "main-script"
oldScript.remove()
bottomDOM.appendChild(newScript)
})

I have a <script class="main-script" src="js/main-dist.js"></script> at the end of the DOM, and use barba.hook to remove it and then add it again我在DOM的末尾有一个<script class="main-script" src="js/main-dist.js"></script> ,并使用 barba.hook 将其删除,然后再次添加

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

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