Dojo On Module

Posted on

Starting from Dojo 1.7, dojo.connect is deprecated and replaced by dojo/on and dojo/aspect. While dojo.connect provides cross-browser capability to manipulate events for dom nodes, the biggest disadvantage is that you can only connect/disconnect one event type at a time even if they have the same event handler. The new dojo/on module came out to address this issue.

The basic syntax for adding event handler for multiple event types is:

on(targetObject, events, eventHandler);

For example:

define(["dojo/on, dojo/touch"], function(on){
    var clickImage = on (this.image, "click, touch.press", this.clickImageHandler);
    //to disconnect the event
    clickImage.remove()
}

You can further refine the target object by adding css class selector to the events parameter. However, this feature does not apply to extension events defined in dojo/gesture and dojo/mouse.
For example, you want to trigger the event only when users single click on an image or double-click on an image if it has class smallImage.

define(["dojo/on"], function(on){
    var clickImage = on (this.image, "click, .smallImage:dbclick", 
            this.clickImageHandler);
}

Another useful use case of dojo/on is to apply on a node list returned by dojo/query. For example:

define(["dojo/on, dojo/query"], function(on,query){
    var clickImage = query(".banner").on("click, .smallImage:dbclick", 
            this.clickImageHandler);
}

Dojo/on module also comes with other some functions for more advanced usage:
on.selector – apply event delegation for extension events
on.emit – return a normalized event object
on.pausable – return a an event object with pause function
on.once – return an event object will self destroy after being called once


2 thoughts on “Dojo On Module

  1. Hi Thanks for blog and this article – Dojo/on module is interesting.
    However, I need more delve on this function “on.pausable ” as it has limited info at dojo website
    Please help.
    Thanks

    Clement

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>