Javascript函数挂钩 [英] Javascript function hooks

查看:116
本文介绍了Javascript函数挂钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:好的,我相信以下解决方案是有效的:

OK, I believe the following solutions are valid:


  1. 使用jQuery AOP插件。它基本上将旧函数与钩子一起包装到函数三明治中,并将其重新分配给旧函数名称。这会导致函数与每个新添加的钩子嵌套。

    如果jQuery不能用于你,只需掠夺源代码,插件中似乎没有任何jQuery依赖项,而且源代码很简单

  1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
    If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.

有一个描述所有钩子及其目标的对象,以及一个用于存储初始未修改函数的对象。添加新钩子时,包装将在原始函数周围重做,而不是重新包装前一个包装函数。

您可以转义嵌套函数,并获取两个要处理的对象。如果你经常添加/删除钩子并且无序,这也可能意味着更容易进行钩子处理。

Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.

I我会选择第一个,因为它已经完成了,我没有表现可担心。由于原始函数不受影响,即使我切换挂钩方​​法,我也只需要重做挂钩添加,这可能只是一些简单的搜索和替换操作。

I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.

是否可以创建一种机制,其中函数A可能有一组钩子(将在函数A)之前/之后执行的函数?

Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?

理想情况下,函数A不会知道挂钩功能,所以我不必修改源代码函数A调用挂钩。类似于:

Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:

A = function(){
    alert("I'm a naive function");
};
B = function(){
    alert("I'm having a piggyback ride on function A!"+
          "And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a 
//piggyback ride on function A! And the fool doesn't even know it!"

我一直试图破解一些事情,但到目前为止还没有运气。

I've been trying to hack something up for a couple of hours, but so far no luck.

推荐答案

看看 jQuery的AOP插件。一般来说,谷歌面向javascript方面的编程。

Take a look at jQuery's AOP plugin. In general, google "javascript aspect oriented programming".

这篇关于Javascript函数挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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