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…
Follow @clientcide on twitter to get notified of new posts.
To follow me personally on twitter, follow @anutron.
September 27th, 2006 at 10:18 am
Note the update to the code; I had a bug in the version I first published.
November 13th, 2006 at 6:31 pm
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?
November 14th, 2006 at 12:35 am
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.
});
November 14th, 2006 at 12:37 am
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().