Event handling in MochiKit
The next lightweight library in this chapter is MochiKit. In this task we will build a script for listing the
onkeydown
and onkeypress
events. After each event we will display which key was pressed with its key code and key string.
Getting ready
All mandatory files, documents, and demos are available on www.mochikit.com. We need to download the whole MochiKit library and save it in our js
folder. Be careful, MochiKit.js
is just the main file that includes all necessary sub-modules from MochiKit (such as, base.js
, signal.js
, DOM.js
, and so on). The landing page for Ajax requests will be ajax/actions.php
:
<?php if($_GET["action"] && $_GET["key"]) { // our logic for processing given data } else { echo "No params provided"; } ?>
How to do it...
Let's start with HTML code:
<table> <tr> <th>Event</th> <th>Key Code</th> <th>Key String</th> </tr> <tr> <td>onkeydown</td> <td id="onkeydown_code">-</td> <td id="onkeydown_string">-</td> </tr> <tr> <td>onkeypress</td> <td id="onkeypress_code">-</td> <td id="onkeypress_string">-</td> </tr> </table>
Include the MochiKit framework:
<script type="text/javascript" src="js/MochiKit/MochiKit.js"> </script>
Define the JavaScript functionality:
<script> connect(document, 'onkeydown', function(e) { var key = e.key(); replaceChildNodes('onkeydown_code', key.code); replaceChildNodes('onkeydown_string', key.string); doSimpleXMLHttpRequest("ajax/actions.php", { action: "keydown", key: key.code}); }); connect(document, 'onkeypress', function(e) { var key = e.key(); replaceChildNodes('onkeypress_code', key.code); replaceChildNodes('onkeypress_string', key.string); doSimpleXMLHttpRequest("ajax/actions.php", { action: "keypress", key: key.code}); }); </script>
Our result is:
How it works...
The connect()
function connects a signal (Mochikit.Signal API Reference) to a slot. In our case, we are connecting our document to the onkeydown
and onkeypress
handlers to call a function(e)
. Parameter e
represents our event object, when the key()
object reference returns key code and string.
replaceChildNodes(node[, childNode[,...]])
is a function of Mochikit.DOM API Reference, which removes all children from the given DOM element and then appends the given childNode
to it.
After each onkeydown
and onkeypress
event we are sending an Ajax call using the doSimpleXMLHttpRequest()
function. In our example, the request from our page looks
like ajax/actions.php?action=onkeydown&key=87
.
There's more...
Any object with connected slots can be disconnected by the disconnect()
or disconnectAll()
functions. In the case that we want to use connect()
just once, we can use the connectOnce()
function and this will disconnect the signal handler automatically once it has fired.
MochiKit allows us to make the most of existing browser-generated events, but some of them are not natively supported by all browsers. MochiKit is able to synthesize these events, which include onmouseenter
, onmouseleave
, and onmousewheel
.