dojo.publish and dojo.subscribe

Let me explain with an example to understand it easily. It is like subscribing to a e-magazine of our interest in real life. So once that magazine is published it will be sent to all those who subscribed. At the same time every subscriber can have their own activities to do with the magazine, say read, copy, print, or do nothing.

Similarly subscribe and publish are the unique features of dojo to trigger a set of actions defined within the subscribe whenever the same topic is published. Interesting right?

The example below will subscribe to school result. So whenever a result is published, the subscribe block will display the name and percentage of the student.

Code:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js.uncompressed.js'></script>
<script type='text/javascript'>
dojo.require("dojo.number");
dojo.require("dojo.NodeList-manipulate");
dojo.ready(function() {
dojo.query('#publish').onclick(function(){
dojo.publish('\result');//publish trigger for topic \result
});
dojo.subscribe('\result',publishResult);//callback to publishResult function
});
function publishResult()
{
var total=0, percentage=0, count=0;
dojo.forEach(dojo.query("input[type=text]:not(:first-child)"), function(data){
count++;
total = total + dojo.number.parse(dojo.query(data).attr("value"));
});
percentage=dojo.number.format(total/count,{places:2});
dojo.query('div.result').append("<p>"+dojo.query("input[type=text]:first-child").attr("value")+"&nbsp; - &nbsp;"+percentage+"%</p>");
dojo.publish('\reset');//publish trigger for topic \reset
}
dojo.subscribe('\reset', function(){
dojo.query("input[type=text]").attr("value","");
dojo.byId("name").focus();
});
</script>
<style type="text/css">
input {
position:absolute;
left:100px;
}
.result {
font-family:verdana;
font-size:12px;
color:#333;
width:250px;
height:auto;
background-color:#CCC;
}
</style>
</head>
<body>
<p>Enter Name and Marks of three subjects. Press Publish button.</p>
<div>Name:
  <input type="text" value="" id="name"/>
  <br />
  Math:
  <input type="text" size="2" maxlength="2" value="" />
  <br />
  Science:
  <input type="text" size="2" maxlength="2" value=""/>
  <br />
  Management:
  <input type="text" size="2" maxlength="2" value=""/>
  <br />
  <input type="button" id="publish" value="Publish" />
  <br />
</div>
<br />
<div class="result">Published Results</div>
</body>

Live Demo:


No comments:

Post a Comment

Please post your comments to help you and others better.