Javascript 函数钩子 [英] Javascript function hooks

查看:40
本文介绍了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.

我会选择第一个,因为它已经完成了,而且我不用担心性能问题.而且由于不影响原有功能,所以即使切换hook方法,也只需要重新添加hook,可能只是一些简单的查找替换操作.

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天全站免登陆