YUI 3 Quick Tip: Adding Your Own Awesome

Luke (@ls_n) posted this snippet in response to a question the other day, and I thought it was worth sharing here as a quick tip.

As with most selector-based idioms, a lot of YUI 3's expressive power comes from what you can do once you have reference to one or more HTMLElements — in YUI 3, that means having a Node reference, which you usually get via Y.one(selector string) or Y.all(selector string). So, Y.one("#foo").doSomethingInteresting is a common pattern.

It's easy to extend YUI 3's expressiveness by adding your own magic to Node (and/or NodeList). Here's one way to make your extension modular and reusable.

With that definition on the page, node++ can be used in any instance. In your implementation code, you would do:

YUI().use('node++', function (Y) {
//use from a single Node:
Y.one('#foo').doAwesomeThing();
//use from a NodeList:
Y.all('p').doAwesomeThing();
});

Note that only the YUI instance(s) to which you bind your node++ module will have access to doAwesomeThing. One feature of this design that you'll like as you build complex apps is that your implementation logic won't need to change if the dependency list for node++ evolves — that will get handled for you automatically at use() time, and the dependency declaration stays with the code to which it pertains.