Hello, everyone,
I recently read an article on Telerik about some things I never knew about JavaScript. Very interesting article!!
It inspired me to learn about something mentioned in a section of that article - dispatch table.
I wrote the following, just playing around trying to learn about dispatch tables, and thought I’d share. As a replacement for switch/case statements. Comments/questions/suggestions welcomed!
<!-- This assumes that you already have jQuery loading either directly or via CDN. -->
<a href='javascript:void(0);' alt='This is title one.' id='title1' class='test'>One</a>
<br /><a href='javascript:void(0);' alt='This is title two.' id='title2' class='test'>Two</a>
<br /><a href='javascript:void(0);' alt='This is title three.' id='title3' class='test'>Three</a>
<div id='testText' style='border:1px solid black;'> </div>
<script type="text/javascript">
$(document).ready(function(){
$('.test').click(function(){
var divAlign = { // Dispatch table - better (most of the time) than a switch/case
title1: function(){$('#testText').css('textAlign','left');},
title2: function(){$('#testText').css('textAlign','center');},
dflt: function(){$('#testText').css('textAlign','right');}
};
var alignIt = function(doWhat){
var doWhat = divAlign.hasOwnProperty(doWhat) ? doWhat : 'dflt' ;
divAlign[doWhat]();
};
alignIt($(this).attr('id'));
$('#testText').html($(this).attr('alt'));
});
});
</script>