Adventures with dojo/on

938
0
11-13-2014 11:22 AM
Labels (1)
ReneRubalcava
Frequent Contributor
4 0 938

The ArcGIS API for JavaScript is currently at version 3.11. Since version 3.0, we all should have mostly abandoned using dojo/_base/connect. If you are really in a pinch working with an older library or maybe something in dojox, at least work with dojo/aspect. By now, everyone should be using dojo/on to listen to events. Maybe you're even using dojo/topic, but that's a whole other blog post.

I'm not going to go into detail on how to use dojo/on, but I thought it would be neat to share a couple of ways you can extend dojo/on to do some cool stuff you might need for particular situations. Some time back, I had need to be able to toggle the eventlistener for a click event on my map. The first time I clicked the map, I want to do a selection and the second time I clicked the map I wanted to run a different method unrelated to the selection. There are a couple of ways I could have gone about this by using dojo/on#pausable or something. But I decided to just extend dojo/on to do what I needed.

define([

  'dojo/on'

], function(on) {

  'use strict';

  var _on = on;

  _on.switchable = function(target, type, listener1, listener2) {

    var funcs

      , index

      , currentListener

      , signal;

    funcs = [listener1, listener2];

    index = 0;

    currentListener = funcs[index];

    signal = _on(target, type, function() {

      return currentListener.apply(this, arguments);

    });

    signal.toggle = function() {

      index = 1 - index;

      currentListener = funcs[index];

    };

    return signal;

  };

  return _on;

});

Then I was thinking about this recent thread and thought, Why can't I make a single use eventlistener?

I'm sure this could come up in certain situations, so I put together a sample you can review. This one as well for a different approach.


You can click on the Speak! button and get an alert message. Click on the Toggle button and click on Speak! again to get a different message. Click on the One time! button and an alert message will pop up in a second. The delay is optional, so you could change the delay to 100ms if you like. Try and click that same button again and nothing happens.

This is just a quick example of stuff you could do depending on your situation and I thought would be fun to share. You can see more tidbits like this on my blog.

Go forth and code my friends.

About the Author
Softwhere Developer at Esri working on cool stuff! Author: Introducing ArcGIS API 4 for JavaScript: Turn Awesome Maps into Awesome Apps https://amzn.to/2qwihrV ArcGIS Web Development - https://amzn.to/2EIxTOp Born and raised in East L.A.