![](/img/trans.png)
[英]cache existing function and add to it and run additions when another function called
[英]Run a function when another function is called
我想知道如何在调用另一个函数时运行一个函数。 addEventListener
只运行“click”,“mouseover”等事件。但是,我想听一个函数调用。
例:
函数1被调用。 之后, 函数2运行,因为它看到函数1被调用。
对于简单函数而不是事件,是否有addEventListener替代方法? 我似乎找不到任何东西。
我的目标是每次用户执行某些操作时简单地运行一个函数,例如当jQuery或其他JavaScript库中隐藏某些东西时,或者只是添加了一些代码的其他外部JavaScript文件。
介绍一种非常黑客的方式
因为你想要实现的目的基本上是攻击一些现有的系统(如果你能控制双方并正确设计你的代码,你不应该遇到这个问题)。
看起来您的函数也是全局声明的。 在这种情况下:1。将现有函数存储在变量中2.用您的实现覆盖该函数3.在开始时调用函数变量
function myFunction(){
//This is the main function
alert('Hello, this is part of the message!');
}
var tempfunc = myFunction;
window.myFunction = function() {
tempfunc();
// do what you need to do in the event listener here
alert('Hello, this is the other part of the message!');
}
编辑:
最初的问题要求原始功能不能修改 ,因此我的解决方案。 因为它们似乎已经改变了。
你将在myFunction
触发一个事件并听取那个事件。
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>
对于简单函数而不是事件,是否有addEventListener替代方法? 我似乎找不到任何东西。
我的目标是每次用户执行某些操作时简单地运行一个函数,例如当jQuery或其他JavaScript库中隐藏某些东西时,或者只是添加了一些代码的其他外部JavaScript文件。
你可以使用jQuery.Callbacks()
var callbacks = $.Callbacks(); function handleCallback1(message) { console.log(message, this) }; function handleCallback2(message) { if (this.tagName === "DIV") { this.style.color = "green"; } else { this.nextElementSibling.style.color = "blue"; } }; $("button, div").on("click", function() { callbacks.fireWith(this, ["called from " + this.tagName]) }); callbacks.add(handleCallback1, handleCallback2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <button>click</button> <div>click</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.