MochiKit by Example

An overview of MochiKit with three real-life examples.

Interactive Web pages, long dreamed of by designers, are finally here—Web interfaces that respond instantly to user commands, with minimal page redraw. All this and more is possible via Ajax (Asynchronous JavaScript and XML), which recently has come into vogue with the Web illuminati.

In JavaScript, and programming in general, the best code is code you don't have to write. For serious projects, this often means using a framework—a collection of useful and reusable code that is tested, optimized and (ideally) peer-reviewed. The better frameworks have automated unit tests to make certain they keep working. Having a good, high-level JavaScript framework, for example, means more time to push the boundaries and less time writing boring building-block code (and then reworking it when the inevitable cross-browser incompatibilities poke their heads up).

MochiKit (www.mochikit.com) is a JavaScript framework that provides tools for dealing with asynchronous requests (Ajax), DOM (Document Object Model) functionality, functional programming tools, dates and times, string formatting, colors, visual effects, events, drag-and-drop ability, sorting and many other features. MochiKit 1.3 is targeted to work on Safari 2.0.2, Firefox (1.0.7, 1.5 and 2.0), Opera 8.5 and Internet Explorer (6 and 7).

This article provides a quick introduction to MochiKit, explains how to get started with MochiKit (with interesting stops along the way) and describes three walk-through examples of varying complexity that also are generic enough to use in your Web applications right now. Ever wanted to round element corners in HTML? Make a link that is clickable only once? Create a dynamic login mechanism? Keep reading!

What's in MochiKit?

Included in MochiKit are algorithms for data structures (including serialization), functional programming, iteration, DOM and CSS manipulation, asynchronous server communication, a signal/slot mechanism for JavaScript events and logging tools. At this point, MochiKit sounds like the C++ STL of JavaScript. Above and beyond what the STL provides C++, MochiKit also provides event handling, drag and drop, colors and visual effects.

On the topic of data structure algorithms, MochiKit provides the powerful iteration tools of filter(), which returns only list elements that match a criteria; find(); map(), which returns the result of list elements run through an operation; and more. MochiKit also provides tools to translate to and from JSON (JavaScript Object Notation) syntax: serializeJSON() and evalJSON(). Above all, MochiKit gives you the power to hook your own objects into MochiKit's magic.

MochiKit's tools for functional programming allow functions to be created dynamically, or they may simply provide more extensive (or less broken) behaviors for functionality provided already in JavaScript. MochiKit's partial() and bind() functions create a version of a function that requires less parameters or rebind JavaScript's this parameter, respectively. In a nutshell, these tools let you create functions dynamically. These two different functions aren't obviously useful right now, but they are powerful when combined with MochiKit's iteration tools.

In addition to these data structure tools, MochiKit allows you to create DOM elements dynamically, convert DOM objects to strings, retrieve elements matching class or type attributes, and swap DOM objects for other DOM objects.

Getting Started with MochiKit

Want to see some MochiKit magic? The Demos page on mochikit.com has several interesting samples. One of MochiKit's examples is an interactive JavaScript Interpreter, executing whatever JavaScript code you enter. In addition, this interpreter provides documentation for MochiKit functions—via help()—returning a clickable link to the passed function.

MochiKit's documentation page also uses some (MochiKit-enabled) JavaScript to display a list of the sub-namespaces of MochiKit. When the main page loads, it dynamically creates a list of sub-namespaces (MochiKit.Async, MochiKit.Base, MochiKit.DOM and so on). Clicking any item in the list expands or collapses the documentation for the namespace. No actual list of functions exists—it's all computed dynamically by (asynchronously) requesting each documentation page from the server, then parsing the DOM of each one. It is worth noting that the documentation on-line corresponds with the release of MochiKit currently in development and not the current “stable” version; each function also lists the version of MochiKit in which it appeared.

Good frameworks have tests to validate their functionality, and MochiKit is no different. The MochiKit test page (see Resources) has almost 800 tests validating MochiKit. This automated framework allows MochiKit to be validated easily on all the supported browsers.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Interactive Web pages

Anonymous's picture

Hi,
thanks for the informative article. chevy trucks

Thanks

Nice document

Jitesh's picture

A great informative stuff about Mochikit DnD.
Thanks for the tutorial.

Correction

jitesh's picture

Sorry mistakenly I have used the word DnD, just omit the word while reading.

Thanks
Jitesh

ucundan?

ucundan's picture

At the Voice On the Net (VON) conference in Toronto, Skype Technologies co-founder and CEO Niklas Zennstrom reported that a mobile version of Skype will be available this year.

helping

Wellnesshotel's picture

thanks for this helpfully article

Re.

zutestrane's picture

sounds like an new fancy name like mootools....

kredit

Anonymous's picture

Thanks for very interesting article. I really enjoyed reading all of your posts. It’s interesting to read ideas, and observations from someone else’s point of view… makes you think more. So please keep up the great work. Greetings

big thx

gregor's picture

Hi,
a big thanks for you - i like your article and will thank you for the examples and the code - I know it's a hard and long work to collect all the information to write such an article! Keep on your work - I will be back sonn and like to read another article written by you :)

Great job

NewSitesBlog's picture

I do congratulate you for the info. I found it to be very useful. Thank You

MochiKit

NBA's picture

Nice! You almost have me convinced. I'm going to put this page in my favorites to go over it better in the future. You covered a couple of things that I would like to be able to address in Javascript as instead of server side.

ask to you

youtube's picture

Why GPLv3 Will Supplant GPLv2

try and report

Chris's picture

Hi,
thanks for the informative article and the work with it! I will try it out and report my results soon.

Kindly regards,
Chris

Hi Should Mochikit.Visual

Balance's picture

Hi Should Mochikit.Visual Round work in all web elements like table, div, jne? I tried to use round in table, div and h1 and only h1 element worked. I used ie7 and firefox 2.0.0.4. Could someone show me a example how should I use this round function in div or other elements. Thanx allready.

looks sweet

Mac Millan's picture

dang it looks phenomenal. It is Java-based, though. IMO that's a good thing, but a lot of hosting services either don't support Java or charge more for Java support.

Thank you

güzel sözler's picture

Unfortunately, not everyone is such a big fan of Java - including myself.

Great post Ryan Wilcox.

JohnZ's picture

Great post Ryan Wilcox. However, I’m not sure I agree 100% about everything you’ve got here. I dont like JS.
Best Regards.

Slow movers are static and need to take classes...

protoman's picture

...prototypic (pronounce: 'Real') programmers are dynamic and never die.

js is....

cms's picture

Hey
I dont like JS...
I'm webmaster about 2 years...
and i use html, css, php, mysql, but sometimes JS is nessesery
at least its use full (if you can use it)

so, today i make my first own js script
and now collect js articles.. like this ;)

thx and greetings

MochiKit

ADAC's picture

Nice! You almost have me convinced. I'm going to put this page in my favorites to go over it better in the future. You covered a couple of things that I would like to be able to address in Javascript as instead of server side.

I'll be looking into this in detail in the near future!

Ajax seems to be the future

Free Software Downloads's picture

At this point, after Web 2.0 wave has pasted, I think the Ajax would be the way to come closer to what the people really want from the web.
MochiKit comes to increase the power of Ajax and offers to programmers a very powerful library. Very good article.

Would have been nice to have

Anonymous's picture

Would have been nice to have the html code for testing...

You should also check out

Anonymous's picture

You should also check out http://mochibot.com/, which is a nice flash content tracker made with monchikit. You'll see lots of sortable tables and XMLHttpRequests. The pages load extremely fast, and you can refresh the data without a full page reload.

Mochibot

MarcoR's picture

Mochibot is really one of the hottest thing i have seen in the last time, try it on your own... Cheers, Marco

SCRIPT tag syntax/usage problem

ch4dwick's picture

For some reason this doesn't work (in fact, it never worked for me in the first place):

<script type="text/javascript" charset="utf-8" src="Mochikit/MochiKit.js" />
<script type="text/javascript" charset="utf-8" src="example1.js" />

Better make it read:

<script type="text/javascript" charset="utf-8" src="Mochikit/MochiKit.js"></script>
<script type="text/javascript" charset="utf-8" src="example1.js"></script>

Best regards. :)

DTD error

Anonymous's picture

The syntax
<script type="text/javascript" charset="utf-8" src="example1.js" />
is allowed in xhtml but not in html

You´re right, but there

Maria's picture

You´re right, but there must be another problem with the syntax.

exactly.

directory's picture

exactly, but it doesn't make much difference. Does it?

One should tell users WHAT

Anonymous's picture

One should tell users WHAT BROWSER/VERSION this isn't working in as it works fine in Firefox.

ZK

ld's picture

Yet another web lib which did not understand Web 2.0...
I recommend everybody to try ZK, Ajax with no javascript (sourceforge project).

ZK apps runs a small JS engine on the browser which only reports browser events, and the web server updates the DOM via xmlrpc. This is Web 2.0 !

Mochikit has mojo

Anonymous's picture

Hmmm, I don't see why ld has to bash Mochikit. Mochikit seems like a very useful way to leverage javascript and web 2.0 is not a sharply defined term.

There was a piece about ZK in the latest Practical Webdesign. I still don't understand why you should use yet another scripting language (ZUML) and at first sight the fancy ZK components do not seem to be easy to customize.

I would vote for JSF, Tapestry or Wicket with a good AJAX framework as a java programmer.

alpella cikolata

alpella's picture

bu sitede alpella cikolatalari var dai

ZK

msn ifadeleri's picture

still don't understand why you should use yet another scripting language (ZUML) and at first sight the fancy ZK components do not seem to be easy to customize i am completely agree

Dear Mr Hammer, not everything is a nail

Xavier's picture

Yet another web lib which did not understand Web 2.0...

  • javascript framework != web lib. JavaScript is not limited to run within a browser, and to run against a web server, java or otherwise
  • javascript != Ajax != Web 2.0 Using "web 2.0" as a synonym of using xmlhttprequest+dhtml is either ill-informed or shameless jumping into the hype
  • promoting your tool != bashing other tools

ZK

Nicholas Petreley's picture

I just checked it out and it looks phenomenal. It is Java-based, though. IMO that's a good thing, but a lot of hosting services either don't support Java or charge more for Java support. Maybe that'll change once Java has been GPLed as far as Sun can take it. Maybe it's changing already and I'm just out of touch with what providers are offering. ;)

Regardless for all other needs (those other than using a hosting service), it looks fabulous.

What Java,

What Java's picture

What Java, Javascript/Mochikit isnt related to Java! btw, I can't get the rounded borders example to work. Mochikit is very well documented for n00bs. I don't understand the advanced library/packinging/classing syntaxes not covered in O'Reilly's Learning Javascript book.

One should tell users WHAT

Anonymous's picture

One should tell users WHAT BROWSER/VERSION this isn't working in as it works fine in Firefox

I meant to say, Mochikit _IS

What Java's picture

I meant to say, Mochikit _IS NOT_ well documented for n00bs, not the other way around. Typo.

Unfortunately, not everyone

ch4dwick's picture

Unfortunately, not everyone is such a big fan of Java - including myself.

I’ve tried your advices,

pilka's picture

I’ve tried your advices, but unfortunatly it doesn’t work. Don’t know maybe i’em doing something wrong. To tell the truth i’m a noob in java.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix