【问题标题】:Add event listener of a method present in another js file添加另一个js文件中存在的方法的事件侦听器
【发布时间】:2017-02-22 10:05:52
【问题描述】:

我正在访问在另一个 js 文件中编写的几个方法。所以我像这样访问它们:

文件 1:

function minit() {
  this.addval = function(val1, val2) {
    return val1 + val2;
  }

  function autoexecute(d) {
    //do something here//
    //raise event//
  }
};

文件2:

var con = new minit();
var result = con.addval(2, 3);

/*
con.autoexecute(function(d) { //Wanna do something like this
  alert(d);
});
*/

上面的事情按预期工作,得到结果.. 现在,假设autoexecute(d) 方法在一段时间后自动调用。我怎么知道方法是否被执行?

所以,我想创建一个autoexecute(d)(在file1中)的事件(在file2中)。

更新: 我希望这个例子能帮助你理解这个问题..

company.js //这是主文件,将在 ui.html中用作参考

function hello(personname) { //this method will invoke automatically after 1 minute..

}

ui.html

<script src="company.js"></script>
<script>
  $(document).ready(function() {
    function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//

      alert("comany.js -> hello function is executed");
    }
  });
</script>

【问题讨论】:

  • 尽量让这个更清晰易懂。
  • 请检查我已经更新了主线程..
  • jsfiddle.net/tgjms546 阅读全文
  • 我读过。如果它在 hello 方法所在的同一个文件中,bye 将被触发。但它们不在同一个文件中......这就是问题所在。 hello() 由comany.js 中的计时器自动触发..
  • 在哪里声明 Bye 是完全不相关的,只要它在同一个 SCOPE 中,而不是在文件中。如果 Bye 是一个全局函数,它将触发,100%

标签: javascript jquery html d3.js


【解决方案1】:

仅当函数具有相同的范围时才能执行此操作(全局范围是最好的情况)。如果 autoexecute 函数具有本地范围,那么你不能这样做。

本质上,像这样覆盖原来的函数...

// keep a reference to the original function
var _autoexecute = autoexecute;

// override the original function with your new one
function autoexecute(d) {
    alert("before autoexecute");  // fired before the original autoexecute
    _autoexecute(d);              // call the original autoexecute function
    alert("after autoexecute");   // fired after the original autoexecute
}

现在,每当调用 autotexecute 时,它都会调用您的新函数,该函数可以处理前后事件,以及调用原始函数。只需删除(可怕的)警报并根据需要替换为事件处理程序。

【讨论】:

  • @DavidM 没有触发器,没有事件。任何在同一范围内引用旧自动执行的函数现在都引用新的。
  • 谢谢阿切尔!但是如何在file2中获得_autoexecute的触发器呢? autoexecute 是全局函数...现在我怎样才能在 file2 中获取它的调用触发器?因为 autoexecute(d) 在 file1..
  • 文件无关。范围很重要。你试过这个吗?
【解决方案2】:

据我所知,如果我错了,有人应该纠正我,没有办法(至少没有一些库)来检测在 javascript 中触发的函数。在这个意义上,函数执行不会触发其他函数可以“处理”的事件。

在您的示例中,您希望一个函数在另一个函数触发后自动触发,您需要做的就是在首先“触发”的函数的末尾调用您想要触发的函数。令人困惑,但希望这会有所帮助。

function handler(){
  alert("main function was fired!");
}
function main(){
  //Code of main goes here and then at the end just add:
  handler();
}

现在,当您的“main”完成其工作时,它将调用 handler 函数。

无论你在哪里定义处理函数,它可以是不同的文件或相同的文件,只要它可以从main 的范围内访问,它就会在它的末尾被触发。它甚至可以在 main 声明之后声明,只要它在 main 被触发之前声明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多