JS中的函数调用事件

Function invoked event in JS?

本文关键字:事件 函数调用 JS      更新时间:2023-09-26

是否可以在调用时将一个函数绑定到另一个函数?例如,它会像这样:

function a(){...}
function b(){...}
b.bind("onInvoke","a");

当b被调用时,a也被自动调用。


编辑:好吧好吧,澄清一下,这不是一个关于连锁的问题。其思想是找到一种执行事件绑定的优雅方法。观察正常函数回调的正常"非优雅"方式:
function handler(){...}
function caller1(){handler(); ...}
function caller2(){handler(); ...}
function caller2(){handler(); ...}
// More callers all over your website everywhere else

可以吗?但如果到处都是我的来电者呢?很难组织或改变事物。

现在观察优解!(如果有的话)

function handler(){...}
// Caller make no reference to handler on creation
function caller1(){...}
function caller2(){...}
function caller3(){...}
// Caller function are still all over the place, all over your website
// Event handler registered later in one location here, doesn't matter where they are phsically
caller1.bind("onInvoke",handler);
caller2.bind("onInvoke",handler);
caller3.bind("onInvoke",handler);

非常像普通的HTML - JQuery事件注册。你不能在用户可能点击的每一张图片上都写上onClick(到处都是),这样组织起来太麻烦了!你只需写一个简单的

 $("img").bind("onClick",click_handler);

为您的整个网站。这是我正在寻找的清单,除了JS函数。

我希望把事情说清楚。


编辑2:需要与IE7一起工作!!JavaScript 1.8.5很棒,但是现在还没有支持它。

您可以使用面向方面的方法来做到这一点。下面是一个简单的例子:

将a()调用附加到函数b()上:

var _b = b;
b = function(){
   _b();
   a();
}

现在调用b():

b();

在这里看到它的作用:http://jsfiddle.net/eZ9wJ/

有不同的解决方案取决于您想要构建的程度。一个简单而灵活的方法是创建一个链接实用程序函数:

function chain() {
   var args = arguments;
   return function() {
      // loop through arguments and invoke all functions
      for(var i = 0; i < args.length; i++) {
         if(typeof args[i] == "function")
            args[i]();
      }
   }
}

返回一个新函数,该函数将按顺序调用所提供的函数。像这样使用:

var myChain = chain(b, a);
myChain();

你可以使用callback:

function a(){
  // some code here
  b();
}
function b(){...}

或观察者模式- http://www.michaelhamrah.com/blog/2008/12/event-pooling-with-jquery-using-bind-and-trigger-managing-complex-javascript/

JavaScript 1.8.5/ECMAScript 5确实定义了一个bind函数,但它没有做你上面描述的;它允许您指定this上下文在调用时将是什么,并且(可选地)允许您硬编码某些参数—curry。