Friday, June 7, 2013

Click events in Dojo are not too tough to master.

I have expanded upon the hello world app I made in Dojo 1.9 here to make the token module I made in the dojo folder named tom.js look like so:

define(["dojo/on", "dojo/dom"], function(on, dom){
   return {
      upfrontMessage: function(id, message){
         var node = dom.byId(id);
         node.innerHTML = message;
      },
      userMessage: function(clickableitem, textfield, id){
         var signal = on(dom.byId(clickableitem), "click", function(){
            var node = dom.byId(id);
            var copy = dom.byId(textfield).value;
            node.innerHTML = copy;
         });
      }
   };
});

 
 

As you can see, the two items in the array to the right of the word "define" populate the two variables in the function. This is how the AMD module stuff works. Then within the define function there is a dictionary of regular functions to which variables may be passed normally. One of them holds the mechanics for a click event while taking in:

  1. the id of a button to consider the clicks for in the DOM
  2. the id of an input field to pull the value from in the DOM
  3. the id of a div in the DOM to put the string pulled from the input field into

Below is the HTML that uses tom.js. You can see it is called in a dojo/tom manner using a route to the module wherein the last bit is the name of the .js file and the preceding bits are the folders to navigate to get there.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title>Tutorial: Hello Dojo!</title>
   </head>
   <body>
      <h1 id="status">Loading...</h1>
      <input type="text" id="userinput" />
      <button id="button">Click me</button>
      <script src="dojo/dojo.js" data-dojo-config="async: true"></script>
      <script>
         require(["dojo/tom"], function(myModule){
            myModule.upfrontMessage("status", "Ready!");
         });
         require(["dojo/tom"], function(myModule){
            myModule.userMessage("button", "userinput", "status");
         });
      </script>
   </body>
</html>

 
 

Our app initially writes "Ready!" Into a div's contents and then again rewrites the div's contents whenever a user clicks the token button. What goes into the div upon the click of the button parallels what a user puts into the sole input field. I figured out the Dojo eventing stuff from here.

No comments:

Post a Comment