调用另一个函数时运行函数 [英] Run a function when another function is called
问题描述
我想知道在调用另一个函数时如何运行函数。 addEventListener
只运行click,mouseover等事件。但是,我想监听进行函数调用。
示例:
函数1 被调用。之后, Function 2 运行,因为它看到 Function 1 被调用。
是否有一个addEventListener替代简单函数而不是事件?我似乎找不到任何东西。
我的目标是每次用户执行某些操作时简单地运行一个函数,就像在jQuery或其他JavaScript库中隐藏某些内容时那样我添加了一些代码的另一个外部JavaScript文件。
I'm wondering how to run a function when another function is called. addEventListener
only runs events like "click", "mouseover", etc. However, I'd like to listen for a function call.
EXAMPLE:
Function 1 is called. Afterwards, Function 2 runs because it saw that Function 1 was called.
Is there an addEventListener alternative for simple functions and not events? I can't seem to find any.
My goal was to simply run a function everytime a user did something like call for when something was hidden in jQuery or by another JavaScript library or just simply another external JavaScript file with some code I added in.
推荐答案
您将触发 myFunction内的事件
并收听该事件。
You will have trigger an event inside myFunction
and listen to that event.
function myFunction(){
//This is the main function
alert('Hello, this is part of the message!');
// trigger the event
var event = new CustomEvent("event", { "detail": "Example of an event" });
document.dispatchEvent(event);
}
// handle here;
document.addEventListener("event", function(){
//This is the secondary function
//or the function I need to run after the main function is called
alert('Hello, this is the other part of the message!');
});
// call main
myFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Simple test!</p>
<p>Long story short, you get message 1, but message 2 never pops up!</p>
这篇关于调用另一个函数时运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!