Event Handlers and Callback Functions - article

本文介绍了一个JavaScript编程技巧,通过使用闭包确保方法作为事件处理器或回调函数时仍能正确引用所属对象。此外,还展示了如何利用高阶函数实现更简洁的多回调管理。

The Trick

The problem is as follows: Methods use this to refer to the object it is a method of. But, when using a method as event handler or callback function, this does no longer point to that object. The trick is to use the closure like behaviour of functions, so that the method will always have access to it's object.

Let's look at an example: We want to use a method of an Alerter class as an event handler.

function Alerter(text) {
  this.text=text;
  var me=this;
  this.invoke=function () {
    alert(me.text);
  }
}
 
var sayHi=new Alerter('Hello, world!');
div.attachEvent('onclick', sayHi.invoke);

So, instead of using this, we use a variable me, that equals this when the invoke method is created. And, in contrast to this, me will keep refering to the correct Alerter object, even when it's passed as a function to the attachEvent method of an HTML element.

Higher Order Programming again

window.setTimeout is an often used function for dynamic webpages. It waits for a given amount of time, and then calls a callback function. The above defined sayHi function can be used as a callback function: setTimeout(sayHi.invoke,2000) will show an alert box after 2 seconds. But what if we want to be extra cool and show 2 alert boxes after those 2 seconds? Then we'd have to create a new function that calls both Alerter objects:

var sayHi=new Alerter('Hello, world!');  
var sayBye=new Alerter('Bye, world!');
setTimeout(function() {sayHi.invoke();sayBye.invoke();},2000);

A nice feature of Microsoft's delegates is that you can create a single composite deligate from several delegates. It looks less messy than inserting an anonymous function. Let's do that in Javascript too, by extending the function prototype.

Function.prototype.andThen=function(g) {
  var f=this;
  return function() {
    f();g();
  }
};

Now we can write:

setTimeout((sayHi.invoke).andThen(sayBye.invoke),2000);
Several callbacks

With the andThen method, it becomes very easy to create an object that allows several other objects to register callbacks.

function Manager() {
  this.callback=function () {}; // do nothing
  this.registerCallback=function(callbackFunction) {
    this.callback=(this.callback).andThen(callbackFunction);
  }
}
 
var manager=new Manager();
manager.registerCallback(sayHi.invoke);
manager.registerCallback(sayBye.invoke);
manager.callback();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值