Rewrite of Behaviour.js in the CNET framework (mootools)

Huh. So this was eaiser than I thought.

In the Download.com Watch List profile page we use the Behaviour library to define a bunch of functionality (er, I mean “I use…” as I wrote all this over a year ago). We’re going to replace Prototype with our new framework (based mostly on Mootools). Behaviour will work in the environment, but it’s 8K that I don’t really want to keep around. So, what the hell, let’s try and rewrite it with Mootools. Well, here it is:

var BehaviourBaseClass = new Class({
	initialize: function(){
		this.behaviours = [];
		var bhvr = this;
		Event.onDOMReady(function(){bhvr.apply()});
	},
	register: function(actions){
		if(! this.behaviours.test(actions))
			this.behaviours.push(actions);
	},
	apply: function(actions) {
		if ($type(actions)!='array') {
			actions = this.behaviours;
		}
		actions.each(function(bhvrs){
			for (bhvr in bhvrs){
				try {
					if($type(bhvrs[bhvr])=='function') {
						$S(bhvr).each(function(el){
							bhvrs[bhvr](el);
						});
					}
				} catch(e){}
			}
		});
	}
});
var Behaviour = new BehaviourBaseClass();

…which compresses down to 425 703 Bytes. Not bad.

Update
Ok, so I rushed to press a little. This code didn’t work when I put it into place. I fixed it, but that brought the file size up to 703 Bytes instead. Still, it’s a 10X reduction…

4 Responses to “Rewrite of Behaviour.js in the CNET framework (mootools)”

  1. Aaron N. Says:

    Note the update to the code; I had a bug in the version I first published.

  2. Joshua Sierles Says:

    Nice work! I’m investigating Mootools seriously now. It seems really nice. Do you have plans to implement some of the behavior of Event::Selectors as well?

  3. Aaron N. Says:

    I only wrote this so that if I had a page that used Behaviour.js this would allow me to avoid rewriting it. I wouldn’t actually use this with new code. Instead, I’d use the actions function for dom elements:

    $S('#exampleId div.classNameExample').action({
    initialize: function() { ...do stuff to every example found...},
    onclick: funciton() { ...do stuff when you click these elements...},
    etc.
    });

  4. Aaron N. Says:

    Oh, note that in the example above, you’d want to execute it after your elements were loaded (probably with the Window.onDomReady() function). Check out http://docs.mootools.net for details on how to use .action() and onDomReady().

Leave a Reply

You must be logged in to post a comment.