Archive for the ‘Code Snippets’ Category

A MooTools Code Riddle For You

January 29th, 2009 by Aaron N.

IMing w/ Valerio today and he shares this method with me, and I swear it’s a damned riddle. If I were in a maze with a minotaur and had to tell you what this code does or die, I might very well die. I did manage to figure it out, but it took me a few moments during which I think I might have had a dumb look on my face and even possibly might have drooled. There’s a reason why Valerio designs frameworks and I do not.

A gold star to the first person who can guess what this function is designed for (note, it’s using some new methods coming in MooTools 1.3, so you’ll have to guess what those do by their names):

Object.duck = function(object){
	return extend(Object.map(Object, function(value, key){
		return function(){
			var o = value.apply(Object, [object].concat(Array.from(arguments)));
			return (typeOf(o) == 'object') ? Object.duck(o) : o;
		};
	}), {unduck: Function.from(object)});
};

For your consideration: $type methods

January 18th, 2009 by Aaron N.

I don’t know why, but I find myself annoyed very slightly by having to type this often:

if ($type('foo') == 'string') ...

On a lark, I whipped this up:

$type.types = ['string', 'element', 'textnode', 'whitespace', 'arguments',
	 'array', 'object', 'string', 'number', 'date', 'boolean',
	 'function', 'regexp', 'class', 'collection', 'window',
	 'document'].map(function(type){
	$type[type] = function(val) {
		return $type(val) == type;
	};
	return type;
});

This provides the ability to do:

if ($type.string(('foo'))) ...

Which saves me a whopping 3 characters, but feels nicer for some reason. Technically, I should name that method .isString(‘foo’) but whatever.

I don’t think I can bring myself to publish or use this one. I like it, but it just doesn’t seem to be worth it.

Link Nudging

December 5th, 2008 by Aaron N.

David Walsh has a nice little effect featured in the footer of his blog. He writes of it:

Link nudging is the process of adjusting the padding on a link slightly to show a simple, tasteful “jump” when you place your mouse over a link. The effect is magnified when mousing on and off a link quickly.

Here’s the code:

$$('#footer-topics-1 a').each(function(el) {
	var fx = new Fx.Morph(el,{ duration:300, link:'cancel' });
	el.addEvents({
		'mouseenter': function() { fx.start({ 'padding-left': 20 }); },
		'mouseleave': function() { fx.start({ 'padding-left': 0 }); }
	});
}); 

New Plugin: Request.Queue

December 1st, 2008 by Aaron N.

The MooTools Request class gives us the option to link together requests so that with a single instance of the class, if you’ve got a request that’s running you can ’stack up’ any new send requests so that they occur one after the other.

This is convenient, but what if you have numerous instances of Request or its subclasses (like Request.HTML) and you want to only have one request running at a time? Or only two?

That’s basically all that Request.Queue does. It lets you register any number of instances of Request or its subclasses with an instance of Request.Queue and then write your code like normal. All requests to server will be queued up and fired off one or two or three at a time (you choose).

I put this class together partially a while back but never really polished it up for release. I spent some time over the holiday break to write up the docs and get it ready for release after I saw this thread in the MooTools Users Group.

Here’s a quick example of what it looks like:

  var num1 = new Request({ url: '/wiki/simple.php', data: {num: 1, sleep: 1}, method: 'get',
      onComplete: function(response){ console.log(response) } });
  var num2 = new Request({ url: '/wiki/simple.php', data: {num: 2, sleep: 1}, method: 'get',
      onComplete: function(response){ console.log(response) } });
  var num3 = new Request({ url: '/wiki/simple.php', data: {num: 3, sleep: 1}, method: 'get',
      onComplete: function(response){ console.log(response) } });
  var myQueue = new Request.Queue();
  //you can add them one at a time
  myQueue.addRequest('num1', num1);
  //or in a single call
  myQueue.addRequests({ num2: num2, num3: num3 });
  num1.send();
  num2.send();
  num3.send();

The above example will only allow the instances of Request to run one at a time. Each one will run and when it gets a response the next item will then be sent. It integrates right into the Request (or Request.HTML or Request.JSON) class when you register it so you don’t have to really change anything.

Note that you can specify how many requests can run at a time. There are also numerous methods and options that you can use to configure things and use the class in numerous ways. I suggest you peruse the docs for all those details.

As always, you can download this from my download builder.

Element shortcuts for Waiter

November 21st, 2008 by Aaron N.

For those of you who haven’t seen my Waiter class, it basically automates the creating of an ajax spinner on a DOM element that’s being updated by an ajax request (or some other process). It’s integrated into Request.HTML so you can enable it with a simple option (useWaiter:true), but occasionally I want to use it outside of an ajax request. I just added two shortcuts to the Element class: wait and release. These basically let you do myElement.wait() to put a waiter over a DOM element. Just a little Friday love.

Here’s a demo in the wikitorial.

Ask Clientcide: How do you randomize your header?

November 21st, 2008 by Aaron N.

I get a lot of emails from people. Sometimes it’s a charitable soul sending me a bug report (via google code) and, sometimes, an even more charitable soul sending me bug fixes (these are my favorite types of people). Then there’s the Clientcide google group, which is where I prefer questions about my code go so that future readers can see the answers, too.

But today I got this email:

Can you write a blog about how you change the images in your
header.

I like your new design so much.

-shin

Awww shucks. Why thank you shin, I like it, too.

So I added a new contact page specifically for suggesting topics you’d like to see me write about (Post a Question / Suggest a Post Topic). And, for starters, I’ll answer this question from shin.
Read the rest of this entry »

Preventing Ajax Request Caching in MooTools – introducing Request.NoCache

November 20th, 2008 by Aaron N.

Ajax requests are, generally speaking, used to update the document or meant to send and fetch new data to and from the server. In Ajax heavy apps, you might end up sending the same request on numerous occasions and not always expect the server to respond with the same results.

This can cause problems with caching. Internet Explorer in particular will see an ajax request with the same parameters and just return the results it got last time, which, well, sucks.

I have this trick that I’ve been using for a while now and I figured I’d release it. The solution is to include a value in your request that’s always different. My solution has been to add a “noCache” value set to the current time. So long as I’m not sending the same request more than once in a millisecond, this solves my problems.

Hot on the heals of yesterday’s plugin (Class.refactor), I’m releasing this tweak on the Request classes that introduces the ‘noCache’ option that will automate this for you. Simply set the ‘noCache’ option to true and you’re all set.

new Request({
    url: '/foo.php',
    data: {...some data...},
    noCache: true
}).send()

Don’t want to set it every time? No problem, just switch the default for the option to true with Class.refactor:

(function(){ //let's not pollute the global namespace
    var setNoCache = function(cls) {
        return Class.refactor(cls, options: {
            noCache: true
        });
    };
    Request = setNoCache(Request);
    Request.HTML = setNoCache(Request.HTML);
})();
//all future instances of Request and Request.HTML
//default to using the noCache functionalty

Man. I’m on a roll this week. You can download this script on the download page and view the docs.

Class::Binds Mutator

July 1st, 2008 by Aaron N.

Jan Kassens, a MooTools contributor, has posted a nifty little trick to help you automatically bind methods to a class. Usually when we reference a method of a class when adding an event, we bind “this” to it to keep our reference to the class (this.addEvent(‘onComplete’, this.complete.bind(this))). This is great until we want to remove that event with removeEvent, which requires we reference the function again. the .bind method creates a copy of the function, so we have to store a reference to it. It’s all very messy. Introducing the Binds mutator. Look for it in the next MooTools patch release, but you can start using it now if you just include the 10 lines Jan has posted.

I wasn’t quite happy with this solution, because it’s too verbose: why always use this.bound.myFn when I always want the bound one? Secondly, I don’t want to do the binding of all these functions by hand. After some discussions on different solutions this is what I come up with as the optimum between speed (don’t worry its faster than the solution above) and usability.

A new so called “class mutator” named Binds. Most of you probably didn’t hear of class mutators before, but you sure have used a class mutator before when you’ve written one or another class. Built in mutators are Implements and Extends...

CiUI Dev on Google Code

April 4th, 2008 by Vladimir Olexa

I’ve created a new development repository on Google Code. I wanted to have a separate development environment for people to work on the library without having to work off of the entire CNET Javascript framework repository. I’ll be posting CiUI-only releases there before merging them with Clientside’s repository.
You can also file CiUI specific bugs and feature requests on there. If you’re interested in joining in the development, please come discuss your ideas to our Google group.

CiUI Dev Google Code repository:
http://code.google.com/p/ciui-dev

CiUI Group
http://groups.google.com/group/ciui

MochaUI – The future of StickyWin?

November 20th, 2007 by Andy L.

Ajaxian today posted about Greg Houston’s MooTools-based MochaUI class that draws draggable, resizable, rounded-corner and dropshadowed boxes without using images. It uses canvas tags and Google’s ExplorerCanvas. Looks like Greg didn’t take advantage yet of Olmo Maldonado’s MooCanvas, but maybe he’ll upgrade. His demo works well across browsers and platforms (with a small bug in FFox/Mac that custom scrollbars can fix).

It might be a while before you see these on CNET, but I’m starting to finally see a happy place between our design and production teams where design gets their rounded corners and dropshadows, and production doesn’t have to deal with the headaches that come with them. I also expect that we’ll see a bunch more development around ExplorerCanvas (and MooCanvas) in the near future.

Greg’s code seems to be pretty well-rounded, but he hopes to add some new features (including modal windows and the aforementioned custom scrollbars). He says this is “an on going [sic] exercise to help me become more familiar with both MooTools and the canvas tag.” Keep up the good work, Greg.

I might add that Aaron lamented via IM, “stickyWin’s days are numbered.” It’s been a good run, stickyWin, but I don’t think we’re done with you quite yet.