Dojo Evented Gotcha

As I continue to work through the world of Dojo Dijits, I have run across another gotcha that I couldn’t find any documentation on and therefore only fixed by trial and error. So here’s my contribution to the world by adding this documentation to the internets.

Scenario: You create a custom component, extending the dojo Evented per the documentation:

define(["dojo/Evented"], function(Evented){
  var MyComponent = dojo.declare([Evented], {
    startup: function(){
      // once we are done with startup, fire the "ready" event
      this.emit("ready", {});
    }
  });
}

However, you build upon the component and end up with something like this:

define(["dojo/Evented"], function(Evented){
  var MyModel = dojo.declare([Evented], {
    CURRENT_INDEX_CHANGE:"onCurrentIndexChange",
    currentIndex:0,
    dispatchEvent: function(evt){
      this.emit(evt, {});
    },
    getCurrentIndex:function(){
      return this.currentIndex;
    },
    setCurrentIndex:function(n){
      if(n != this.currentIndex){
         this.currentIndex = n;
         this.dispatchEvent(this.CURRENT_INDEX_CHANGE);
      }
    }
  });
}

AND THEN, you end up getting this error in your browsers console:

TypeError: target.ownerDocument is undefined

ending in bafflement. 😦

Reason:
“dispatchEvent” is used in dojo/on, which Evented extends, causing a conflict.

Solution! Rename your “dispatchEvent” function to something new, so you end up with:

define(["dojo/Evented"], function(Evented){
  var MyModel = dojo.declare([Evented], {
    CURRENT_INDEX_CHANGE:"onCurrentIndexChange",
    currentIndex:0,
    dispatchEventWTF: function(evt){
      this.emit(evt, {});
    },
    getCurrentIndex:function(){
      return this.currentIndex;
    },
    setCurrentIndex:function(n){
      if(n != this.currentIndex){
         this.currentIndex = n;
         this.dispatchEventWTF(this.CURRENT_INDEX_CHANGE);
      }
    }
  });
}

The end.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s