dojo.connect: A Powerful Object and Event Listener

By  on  

One of the pieces of the Dojo Toolkit I've been really impressed with is dojo.connect. This connect method not only listens to DOM events but also allows you to listen to when a regular function is executed. Lets examine what dojo.connect is and the different methods by which you can use dojo.connect within any Dojo application.

dojo.connect's Signature

dojo.connect = function(
	obj,		//Object|null
	event,		//String
	context,	//Object|null
	method,		//String|Function
	dontFix		//Boolean
) //.....

A more detailed explanation of each argument (as taken from the Dojo documentation):

  • obj: The source object for the event function. Defaults to dojo.global if null. If obj is a DOM node, the connection is delegated to the DOM event manager (unless dontFix is true).
  • event: Name of the event function in obj. I.e. identifies a property obj[event].
  • context: The object that method will receive as "this". If context is null and method is a function, then method inherits the context of event. If method is a string then context must be the source object object for method (context[method]). If context is null, dojo.global is used.
  • method: A function reference, or name of a function in context. The function identified by method fires after event does. method receives the same arguments as the event. See context argument comments for information on method's scope.
  • dontFix: If obj is a DOM node, set dontFix to true to prevent delegation of this connection to the DOM event manager.

dojo.connect returns a handle that you will need to remove the connection later. Also note that any arguments passed to the object (function) will be received by the listener! Holy hell that's useful!

Example Usages: DOM Node Event Handling

var eventHandle = dojo.connect(dojo.byId('myElement'), 'onclick', null, function() { //null = dojo.global
	alert('you clicked myElement');
});

//...or:

var eventHandle = dojo.connect(dojo.byId('myElement'), 'onclick', function() { //context isn't required
	alert('you clicked myElement');
});

When myElement is clicked, my messaged is alerted.

Example Usages: Object Handling

var someFunction = function() {
	alert('run!');
};
var val = dojo.connect(null, 'someFunction', null, function() { //null = dojo.global
	alert('you ran someFunction!()');
});

When someFunction is called, my listener function alerts the message. How cool is that?!

Example Usages: NodeList Event Handling

dojo.query('.myElements').connect('onclick', function() { //"this" becomes the "current" element
	alert('you clicked this link');
});

Event handling even works on dojo.connect -- you don't need to cycle through each element in the collection to add the event listeners individually.

Example Usage: Removing an Event

var eventHandle = dojo.connect(dojo.byId('myElement'), 'onclick', function() { //context isn't required
	alert('you clicked myElement');
});

//....
//something happens; we want to remove the event listener
//....

dojo.disconnect(eventHandle);

We pass the handle provided by dojo.connect to disconnect the listener.

That's just a quick taste of what you can do with dojo.connect. Be sure to check out Dojo and experiment with the different ways you can use dojo.connect. Since dojo.connect is one of the core methods of the library, dojo.connect is used everywhere. dojo.connect also plays an important role within Dijit, Dojo's UI branch.

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    Smooth Scrolling with MooTools Fx.SmoothScroll

    I get quite a few support requests for my previous MooTools SmoothScroll article and the issue usually boils down to the fact that SmoothScroll has become Fx.SmoothScroll. Here's a simple usage of Fx.SmoothScroll. The HTML The only HTML requirement for Fx.SmoothScroll is that all named...

  • By
    Creating Spacers with Flexbox

    I was one of the biggest fans of flexbox before it hit but, due to being shuffled around at Mozilla, I never had the chance to use it in any practice project; thus, flexbox still seems like a bit of a mystery to me.  This greatly...

Discussion

  1. Hott Dogg

    Hello. Thanks for useful article :)
    I have a question. How can we disconnect an event, if we don’t have a return value of .connect method?
    I mean if we use something like this:

    dojo.query("...").connect("onmouseenter", function(evt) { .... });
    

    How can we disconnect onmouseenter event or just replace it with another event?
    Thank

    • Pixelknecht

      To disconnect evenst, simply use

      .disconnect()

      so, in your case it might be something like this:

      var connected = dojo.query('...').connect(yourObject, 'event', function(){ // code goes here... });
      
      dojo.disconnect(connected);

      although I know this line of code would be pretty senseless ;)

    • Hott Dogg

      Sorry, but seems you didn’t read attentively what I wrote
      I have a .connect code that doesn’t save result to a variable, so I can’t just use dojo.disconnect(connected);
      What should I do instead?

  2. marius

    Hi!
    Thanks a lot for the great articles about Dojo! Regarding this post (about dojo.connect) I don’t see in what situation/case the second example (object handling) would be useful. Could you give me an example?
    Thank you

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!