cuongle
cuongle

Reputation: 75326

Issue on dojo onlick event on html button

I am a new kid with dojo, I got weird issue which I take lots of time and have not yet found out, assume I have 4 buttons:

<button id="btnMoveFirst" data-dojo-type="dijit.form.Button" iconclass="plusIcon">
    &lt; &lt;</button>
<button id="btnMovePrev" data-dojo-type="dijit.form.Button" iconclass="plusIcon">
    &lt;</button>
<button id="btnMoveNext" data-dojo-type="dijit.form.Button" iconclass="plusIcon">
    &gt;</button>
<button id="btnMoveLast" data-dojo-type="dijit.form.Button" iconclass="plusIcon">
    &gt; &gt;</button>

And use dojo with event onclick as below:

dojo.connect(dijit.registry.byId('btnMoveFirst'), "onclick",  function(evt){
    alert('test1');
});

dojo.connect(dijit.registry.byId('btnMovePrev'), "onclick",  function(evt){
     alert('test2');
});

dojo.connect(dijit.registry.byId('btnMoveNext'), "onclick",  function(evt){
     alert('test3');
});

dojo.connect(dijit.registry.byId('btnMoveLast'), "onclick",  function(evt){
     alert('test4');
});

But when I click any one of 4 buttons, or even any button in form, I got 4 alerts instead of only correct one.

Does anyone know this?

Upvotes: 0

Views: 2016

Answers (1)

phusick
phusick

Reputation: 7352

The reason for I got 4 alerts instead of only correct one is the combination of:

  • buttons are not instantiated in the moment of invoking dojo.connect → wrap your code into dojo/ready
  • connecting to method which does not exist → connect to onClick instead of onclick

Based on the discussion, here is the way how to write the code in the question in Modern Dojo:

require([
    "dojo/ready",
    "dojo/aspect",
    "dijit/registry",
    "dijit/form/Button"
], function(
    ready,
    aspect,
    registry
) {

    ready(function() {

        // dojo/Evented
        registry.byId("btnMoveFirst").on("click", function() {
            console.log("first");        
        });

        // dojo/aspect 
        // it's the same as dojo.connect in previous versions
        // nevertheless this is not recommended
        aspect.after(registry.byId("btnMoveLast"), "onClick", function() {
            console.log("last");            
        });       

    });

});

The working example: http://jsfiddle.net/phusick/355MT/

Upvotes: 1

Related Questions