Login Register

Connecting Multiple Events

Multiple Listeners

Connect also transparently handles multiple listeners. They are called in the order they are registered. This would kick off two separate actions from a single onclick event:

var handlerNode = document.getElementById("handler");



dojo.event.connect(handlerNode, "onclick", object, "handler");

dojo.event.connect(handlerNode, "onclick", object, "handler2");

We didn't have to change the API we were using, rewire anything for multiple events, etc. It all just works. Now every time you click the node, and object.handler() gets called and then object.handler2() gets called.

Finally, note that connect can take an array of objects as input:

dojo.event.connect(

dojo.byId("id"),“onclick",

listenerObj, “handleOnClick");

Disconnection and Multi-Connection

Connecting is one thing, but what about when you want to stop listening? dojo.event.disconnect() will stop the listening arrangement between functions, but must be pass exactly the same arguments as were passed to connect in order to ensure successful disconnection.

If there's anything that can trip up new users of dojo.event.connect(), it's inadvertently connecting multiple times. Very often, a piece of code will get called multiple times, and it will contain a dojo.event.connect() call. The developer is then surprised when their listener function is called multiple times for every time the source function fires. What to do?

Connecting Once And Using Keywords

One option is to move your connect() call to a location that will get invoked only once, but sometimes that's just not feasible. An optional argument to connect() ensures that the same arguments to connect passed multiple times will result in only one connection between functions. Unfortunately, it's the 8th parameter. Ugh. The last thing we want to do is remember 8 different parameters. The best answer in this scenario is to use the keyword-argument version of connect, aptly named kwConnect(). To use it, we have to give the parameters we've been using so far names. Here's our object connection example using kwConnect() and the once

parameter:

dojo.event.kwConnect({

srcObj: exampleObj,

srcFunc: "foo",

targetObj: exampleObj,

targetFunc: "bar",

once: true

});

As I'm sure you've already guessed, there's an analogous kwDisconnect method. Just pass it what you pass kwConnect, naturally.