views:

465

answers:

2

I'm running into a problem using dojo.connect() to connect an 'onclick' event with this button:

<button dojoType="dijit.form.Button" widgetId="inbox_button" id="inbox_button">Inbox</button>

and the code making the connection is:

var inbox_button=dojo.byId("inbox_button");
dojo.connect(inbox_button,'onclick',function(){
    var container=dijit.byId("center");
    container.addChild(new dijit.layout.ContentPane({region: "left", content: "...", style: "width: 100px;"}))
});

However, instead of executing the function when the button is clicked, ANY onclick event triggers the function, and I end up with a lot of children containers.

Even though I'm pretty certain the .connect() function should be available as part of dojo's base functionality, I've 'required' it explicitly:

dojo.require("dojo._base.connect");

Any ideas as to why this might be happening?

A: 

To answer my own question: never underestimate the value of dojo.addOnLoad!

I feel that since the button was being used as a widget, it's ID wasn't registered until after Dojo finished loading, and since the connection code wasn't within an addOnLoad block, it couldn't find the (not yet loaded) button. The reason, then, that the method was firing on every click event was because of the way Dojo deals with null objects in the connect() function: it ignores them and instead uses dojo.global (Dojo's version of document.window) as the object.

I hope this helps anyone else who may have come across a similar issue!

Daniel
+3  A: 

As you say, if you run that code before the DOM is ready, dojo.byId("inbox_button") will return null. So your connect is actually doing:

dojo.connect(null, "onclick", function() { ... })

.. if the 1st arg to dojo.connect is null, the global or 'window' object will be used.

But, that's just one error here. Your button element is getting widget-ized, and turned into a dijit.form.Button. So you should be connecting to the widget's onClick method here, not the node's onclick:

dojo.connect(dijit.byId("inbox_button"), "onClick", function() { ... });

Also, to be clear, you should never have to dojo.require anything in dojo._base, that's the promise that dojo.js makes to you - its all bundled in.

Sam Foster
Thanks, I made that change to all my buttons. One question though: using dojo.byId("x") and onclick was working, so why would it be preferred to use dijit/onClick?
Daniel