【问题标题】:How to call $(document).ready(function() {…}); from another file JS如何调用 $(document).ready(function() {...});从另一个文件 JS
【发布时间】:2018-08-21 11:10:57
【问题描述】:

我想知道如何在不从另一个 js 文件重构的情况下调用下面的函数。

$(document).ready(function() {

  check();

  function check () {
    setTimeout(function(){
      location.reload(true);
    }, 10000);
  }

});

我看到这个问题存在一个非常老的问题,但我不明白如何为我的函数使用答案。 StackOverflow answer from another question

我想通过链接查看我的功能示例和建议的解决方案。

我的例子不能正常工作:

//= require rspec_helper
//= require background_index
//= require sinon



describe("Background Index, timeout after 10s", function() {
  // Tweak for testing
  var doc_ready = $.readyList[0]();

  it ("Reload the location", function(){
    clock = sinon.useFakeTimers();

    var check = doc_ready.check();
    var set_timeout = doc_ready.setTimeout();
    /*var stub_check = sinon.stub(check, "check");
    var stub_timeout = sinon.stub(timeout, "setTimeout");*/


    timedOut = false;



    setTimeout(function () {
      timedOut = true;
    }, 1000);


    timedOut.should.be.false;
    clock.tick(10010);
    timedOut.should.be.true;

    clock.restore();
  });

});

【问题讨论】:

  • 这很好用,你只需要确保在加载其他 JS 文件之前加载 jQuery。
  • 你不能这样称呼它,它不是一个函数。 $(document).ready(...) 是一个函数调用
  • 所以我需要重构?但是我发布的答案是可能的。能否请您解释给我理解。
  • @Jakub - 这可能是一个展示主动性的机会,让您的 CTO 进行工作重构以供批准。在我看来,这样的重构将是微不足道的。
  • @Jakub - 您认为您的应用程序中存在多少对 document.ready 的调用,因为顺序很重要。

标签: javascript sinon teaspoon


【解决方案1】:

这是根据您粘贴的答案重写的。

$(document).ready(check);

  function check () {
    setTimeout(function(){
      location.reload(true);
    }, 10000);
  }   

// In the test file
TestFile.prototype.testDocumentReadyContents = function () {
  check();
}

更好的方法是使用<script src="./path-to-file"> 在您的 HTML 中包含所有 JS 文件,然后按照您希望调用它们的顺序调用函数。

【讨论】:

  • 好的,另一个答案是说 Hack 部分只能使用 TestFile.prototype.testDocumentReadyContents = function () { $.readyList[0](); } 如果你检查的是与其他部分分开的是我不明白的。
  • 我从其他答案中了解到使用 $.readyList[0](); 从我正在测试的 JS 文件中访问它
  • @ChaosPandion:你能看看
  • @Jakub 他发布了 2 种不同的方式,其中我复制的是“好方式”。我认为你应该去那个。否则,只需复制“hacky”部分并使用它而不是我的答案中的最后 3 行。
  • 我不能重构代码,因为我被禁止这样做。我无法理解如何使用 $.readyList[0]() 来测试那个 JS。我完全错过了那部分。
猜你喜欢
  • 2010-12-24
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2010-12-22
  • 2011-05-22
相关资源
最近更新 更多