30 Days of Mootools 1.2 Tutorials - Day 14 - Periodical and Intro to Hashes

- Troy

Periodicals and Hashes with Mootools 1.2

If you haven’t already, be sure and check out the rest of the Mootools 1.2 tutorials in our 30 days series.

Today’s tutorial is going to look at two areas, the first is .periodical(); and then we are going to get an introduction to hashes. Periodical will do pretty much what it says—periodical will fire a function, periodically. Hashes on the other hand are sets of key/value pairs. Don’t worry if you are not familiar with hashes yet—we are going to do a quick introduction today and provide a few links for further reading. And like everything with Mootools, once you see it the right way, its easy to use and incredibly helpful.

.periodical()

The Basics

All you have to do is tack .perdiodical(); onto the end of a function, and just like that your function will fire periodically. Like always, there are few things you will need to define. For starters, you will need the function you want to attach periodical to, as well as how often you want to fire (measured in milliseconds).

var periodicalFunction = function(){
	alert('again');
}
 
window.addEvent('domready', function() {
        //number at the end indicates how often to fire, measure in milliseconds
	var periodicalFunctionVar = periodicalFunction.periodical(100);
});

Built in .bind();

.periodical includes a great feature - it will automatically bind a var as the second parameter. For example, if you wanted to pass a var outside the domready, you could bind it to the function you are firing periodically by setting it as the second parameter.

window.addEvent('domready', function() {
        //pass something to a var
        var passedVar = $('elementID');
        //now periodicalFunction will be able to use "this" to refer to "passedVar"
	var periodicalFunctionVar = periodicalFunction.periodical(100, passedVar);
});

Stopping a periodical function

$clear()

To stop a function from firing periodically once you have initiated it (like we did above), you can use $clear();. Its very simple to use:

//we clear the var that we passed the function and periodical to
$clear(periodicalFunctionVar);

Example

To put it all together, let’s use a few of the things we have learned up to now (and a few we haven’t) to create a timer. First, set up the timer html, and then we are going to want to include a start button, a stop button and a reset button. Also, we should create a bar that will get longer as time goes on. Finally, we should have a place to show how long the timer has been going.

<button id="timer_start">start</button>
<button id="timer_stop">pause</button>
<button id="timer_reset">reset</button>
 
<div id="timper_bar_wrap">
 
</div>
 
 
<div id="timer_display">0</div>

Now, for the Mootools.

var timerFunction = function(){
        //each time this function is called
        //the var currentTime will increment by one
        //more on this below
        //also notice the use of "this.counter"
        //"this" is the hash
        //and "counter" is the key
        //again, more on this below
	var currentTime = this.counter++;
        //here we change the content of the timer display div to the current time
	$('timer_display').set('text', currentTime);
        //this changes the style width, letting us easily create a timer bar
	$('timer_bar').setStyle('width', currentTime);
}
 
window.addEvent('domready', function() {
        //this is a simple hash with one key/value pair
	var currentCounter = new Hash({counter: 0});
        //we initiate our periodical and pass and bind the hash var
	var simpleTimer = timerFunction.periodical(100, currentCounter); 
 
        //since we dont want the timer starting onload, we stop it
	$clear(simpleTimer);
 
        //add an event to the start button
        //this sets the timer going again
        $('timer_start').addEvent("click", function(){
		simpleTimer = timerFunction.periodical(100, Site);
	});
 
        //this clears the periodical, and highlights the timer bar
	$('timer_stop').addEvent("click", function(){
		$clear(simpleTimer);
		$('timer_bar').highlight('#EFE02F');
	});
 
	$('timer_reset').addEvent("click", function(){
                //reset first clears the periodical
		$clear(simpleTimer);
                //and sets the counter to 0
                //more on this later
		currentCounter .set('counter', 0);
                //
		$('timer_display').set('text', Site.counter);
		$('timer_bar').setStyle('width', 0);
	});
});



0

Intro to Hashes

Creating a new hash

There are a few things in that example you may not have seen before. First of all, we are using a hash. Hashes are sets of key/value pairs, and they are similar to an array in that they hold multiple objects, but each object they hold is also assigned a key. First, lets look at how to build a new hash:

var hashVar = new Hash({
     'firstKey': 0,
     'secondKey': 0
});

So you put the key on the left and the value on the right (as an aside to those of you out there who are familiar with hashes, we are only covering hashes at the most fundamental level. We are going to reserve storing functions within hashes until we have had a chance to talk about classes). Anyhow, there are many advantages to using a system like this. First of all, you can multiple sets in a single object. Retrieval becomes much simpler and its great for keeping complex data organized.

.set() and .get()

You can also use the familiar .set() and .get() with hash keys. When you want set, you declare the key, then the value to set to. When you want to get, you just declare what key you want. That’s all there is to it.

//assuming the hash above
//here we set the firstKay to 200
hashVar.set('firstKey', 200);
 
//here we get the value of firstKey, which is now 200
var hashValue = hashVar.get('firstKey');

You can also get a value by refering to hash.keyName:

var hashValue = hashVar.firstKey;
//is the same as
var hashValue = hashVar.get('firstKey');

Adding a new pair to a hash

.extend();

You can add a new set of key/value pairs (or several sets) with .extend(). First, let’s create a new pair object.

//this is a generic object
//it contains key value pairs
//but not the capabilities of a hash
var genericObject = {
    'third': 450,
    'fourth': 89
};

If we want to add this set of pairs to our existing hash, we just .extend(); the original hash to make room.

//now hashVar contains all the pairs within genericObject
hashVar.extend(genericObject);

Note: Any duplicate keys will be overridden by the second set. So, if you have “firstKey”: “letterA” in the original hash, and you extend it with the “firstKey”: “letterB,” the resulting hash would read, “firstKey”: “letterB.”

Combining two hashes

.combine();

This lets you combine two hashes, and keeps the original if there are duplicate keys. Other than that, works just like .extend.

Removing pair from a hash

.erase();

We have seen this one before. It works just like you would expect. You state the hash, then tack on .erase();, and finally you put the ‘key’ inside the (parenthesis)

hashVar.erase('firstKey');

Hashes and .each()

Hashes have a special relationship with .each(), and when you iterate through a hash, the each function will pass you the “value” as the first parameter and the “key” as the second - like when you use .each on an array and it includes each “item” as the first parameter.

hashVar.each(function(value, key) {
    //this would send up one alert for each pair in the hash
    alert(key + ":" + value);
});

To Learn More…

That’s all we are going to cover on hashes for now. As we get further into the series, we’ll find some opportunities to look at other capabilities. But for now, hopefully this can serve as an introduction to the concept if you are new to this sort of thing. Soon enough, we are going to be covering classes, and then things will really start to come together. In the meantime, check out the hashes section of the docs.

Download a zip with everything you need to get started

Including the Mootools 1.2 core, the examples above, an external javascript file, a simple html page and a css file.

Tomorrow’s Tutorial

Learn how to set up and configure a Mootools slider

Questions, Comments, Suggestions

If you have anything to add to our discussion on Hashes or you are curious about the capabilities of the periodical function, feel free to drop a note. Any other questions or suggestions are welcome. Thanks and hope you find these tutorials useful.

Bookmark and Share

Comments (7)
  1. Daniel


    Ahh, an extra nice post today Troy! This is probably going to help a LOT of folk. :)
  2. Peace


    The download link not found, hope you fix it.

    Acctually I hope you can do some introduction on how to use mootools to build classes because this always confuse me (The doc is really that simple, and works by other superiors are not my level).

    And say thank you again for your work.
  3. Troy


    Thanks for letting us know about the download, Peace. Should be working now. As far as classes, we are going to be covering them in the the last half of the series, so keep an eye out. We try to keep a list of the upcoming tutorials updated on Day 1.
  4. Justin


    Don't press start more than once without pressing pause in between. If you do, the counter speeds up dramatically and you can't pause it anymore!

    Click start 5 or 6 times. Man! It goes really fast.
  5. Troy


    neat :), thanks for catching that. I'll be sure to amend the tutorial with a fix for that.
  6. Huy


    Great work Troy,

    I like your clear &amp; concise tutes.

    Regarding the timer problem, you just need to put this line inside the addEvent block of the timer start button

    $clear(simpleTimer);

    This will stop the multiple click issue.

    Also I believe those lines with reference to Site should read currentCounter

    e.g : simpleTimer = timerFunction.periodical(100, Site);

    should be simpleTimer = timerFunction.periodical(100, currentCounter);
  7. Troy


    Thanks much Huy :)

    I will be sure to amend the tutorial.


Leave a Reply