函数执行完成后如何调用函数? - JavaScript
我正在使用一个用户控件,该控件具有一组在执行操作时调用的 JavaScript 函数。该用户控件在应用程序的很多地方使用。
当内置 JS 函数之一完成执行时,我需要在页面上触发自定义 JS 函数。
有没有办法让我附加一个函数,当另一个函数完成执行时要触发该函数?我不想更新内置的 JS 函数来调用此页面的 JS 函数。
希望这是有道理的。
I am working with a user control that has set of javascript functions that are called when an action is performed. This user control is used in a lot of places in the application.
When one of the inbuilt JS function completes execution, I need to fire a custom JS function on my page.
Is there a way for me to attach a function to be fired when another function completes execution? I don't want to update the inbuilt JS function to call this page JS function.
Hope this makes sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最丑陋和最好的解决方案是对内置函数进行猴子修补。假设内置函数称为“thirdParty”:
我们实际上创建了内置函数的修改版本,而没有触及原始版本。
The ugliest and best solution is to monkey-patch the built-in function. Assume the built-in function is called "thirdParty":
We've essentially created a modified version of the built-in function without ever touching the original version.
由于 Javascript 是高度动态的,您可以修改原始函数而无需修改其源代码:
Since Javascript is highly dynamic you can modify the original function without modifying its source code:
您可以使用几种设计模式来实现此目的,具体取决于特定代码(您尚未共享的代码)以及可以更改和不能更改的内容:
添加回调:
选项 1:向某些现有代码 ,您可以使用以下方式调用它:
选项 2:包装以前的函数:
因此,现在任何时候有人这样做:
它都会调用原始方法,然后调用您的函数。
There are a couple design patterns you could use for this depending upon the specific code (which you have not shared) and what you can and cannot change:
Option 1: Add a callback to some existing code:
So, you can call this with:
Option 2: Wrap previous function:
So, now anytime someone does:
it will call the original method and then call your function.
您基本上是在尝试进行回调。由于您没有提及您正在谈论的函数(如代码中所示),因此最好的办法基本上是包装该函数(快速而肮脏)并使其与回调一起使用。
这样你就可以向它传递一个 Lambda(匿名函数)并在完成后执行你想要的任何操作。
更新以演示如何添加回调:
You're basically trying to do callbacks. Since you're not mentioning what functions you're talking about (as in code), the best thing to do would be basically to wrap the function, -quick and dirty- and make it work with callbacks.
That way you can pass it a Lambda (Anonymous Function) and execute anything you want when it's done.
Updated to demonstrate how to add Callbacks: