Search code examples
moduleyui3

Howto add custom utility / module in YUI3


I would like to register a custom utility / module within YUI3 that is passed one or more custom node(s) and that can be called like this (without having to instantiate it):

YUI().use('myCustomModule', function (Y) {
 Y.one('nodeToProcess').myCustomUtility(config);
 Y.all('manyNodes').myCustomUtility(config);
});

jQuery offers a similar functionality.

I know that a custom module in YUI3 is defined like this:

YUI.add('myCustomModule', function(Y) {
// my Code here
}, '0.1', {
requires : ['node']
});

But what I don't understand is how to setup my custom module, so that I can call it like described. Do I have to extend Plugin / Widget class or use Y.Namespace() to get this to work? (see http://www.slideshare.net/caridy/building-yui-3-custom-modules )


Solution

  • You may want to try this:

    <!doctype html>
    <head>
        <meta charset="utf-8">
        <script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
        <script>
    YUI.add('joiz', function(Y) {
    
        function joizMagic(context, config) {
            alert(config.name + ' says: "' + this.getContent() + '"');
        }
    
        // define a function that will run in the context of a
        // Node instance:
        Y.Node.addMethod("joizMagic", joizMagic);
    
        // extend this functionality to NodeLists:
        Y.NodeList.importMethod(Y.Node.prototype, "joizMagic");
    
    }, '0.1.1' /* module version */, {
        requires: ['node']
    });
    YUI().use('joiz', function (Y)
    {
        Y.all('.message').joizMagic({ name: 'Beatrice' });
    });
        </script>
    </head>
    <body>
        <div class="message">Hello World!</div>
        <div class="message">I'm still here!</div>
    </body>
    </html>