添加另一个js文件中存在的方法的事件侦听器 [英] Add event listener of a method present in another js file

查看:89
本文介绍了添加另一个js文件中存在的方法的事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在访问用另一个js文件编写的几种方法.所以我正在这样访问他们:

I am accessing few methods written in another js file. So i'm accessing them like this:

文件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)方法在一个时间间隔后自动调用.我怎么知道该方法是否执行?

Above things are working as expected, getting result.. Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?

因此,我想创建一个autoexecute(d)(在file1中)的事件(在file2中).

So that, I want to create an event(in file2) of autoexecute(d)(in file1).

更新: 我希望这个例子可以帮助您理解问题.

UPDATE: I hope this example will help you to understand the issue..

company.js //这是将在ui.html

company.js //this is the main file which will be used as a reference in 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>

推荐答案

仅当函数具有相同的作用域(全局作用域是最佳情况)时,您才能执行此操作.如果autoexecute函数具有本地作用域,则无法执行此操作.

You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.

本质上,像这样覆盖原始功能...

In essence, override the original function like this...

// 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时,它将调用您的新函数,该函数可以处理事件之前和之后,以及调用原始函数.只需删除(可怕的)警报,然后根据需要替换为事件处理程序即可.

Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.

这篇关于添加另一个js文件中存在的方法的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆