Example: IO Plugin

This example shows how you can use Widget's plugin infrastructure to add additional features to an existing widget.

We create an IO plugin class for Overlay called StdModIOPlugin. The plugin adds IO capabilities to the Overlay, bound to one of its standard module sections (header, body or footer).

Creating an IO Plugin For Overlay

Setting Up The YUI Instance

For this example, we'll start from the Widget IO plugin (gallery-io-plugin) created in the widget plugin example, pull in overlay, json utility module, and the plugin module. The Widget IO plugin will pull in the dependencies it needs, the main one being io to provide the XHR support. The json and modules provide the support we need to parse/transform JSON responses into HTML.The code to set up our sandbox instance is shown below:

YUI({...}).use("overlay", "json", "gallery-io-plugin", "escape", function(Y) {
    // We'll write our code here, after pulling in the default Overlay widget,
    // the IO utility, the Plugin.WidgetIO base class along with the
    // Substitute and JSON utilities
});

Using the overlay module will also pull down the default CSS required for overlay, on top of which we only need to add our required look/feel CSS for the example.

Note: be sure to add the yui3-skin-sam classname to the page's <body> element or to a parent element of the widget in order to apply the default CSS skin. See Understanding Skinning.

<body class="yui3-skin-sam"> <!-- You need this skin class -->

StdModIO Class Structure

The StdModIO class will extend the Plugin.WidgetIO base class. Since WidgetIO derives from Pluing.Base and hence Base, we follow the same pattern we use for widgets and other utilities which extend Base to setup our new class.

Namely:

  • Setting up the default attributes, using the ATTRS property
  • Calling the superclass constructor
  • Setting up the the NAME property
  • Providing prototype implementations for anything we want executed during initialization and destruction using the initializer and destructor lifecycle methods

Additionally, since this is a plugin, we provide a NS property for the class, which defines the property which will refer to the StdModIO instance on the host class (e.g. overlay.io will be an instance of StdModIO)

.
StdModIO = function(config) {
    StdModIO.superclass.constructor.apply(this, arguments);
};

Y.extend(StdModIO, Y.Plugin.WidgetIO, {
    initializer: function() {...}
}, {
    NAME: 'stdModIO',
    NS: 'io',
    ATTRS: {
        section: {...}
    }
});

Plugin Attributes

The StdModIO is a fairly simple plugin class. It provides incremental functionality. It does not need to modify the behavior of any methods on the host Overlay instance, or monitor any Overlay events (unlike the AnimPlugin example).

In terms of code, the attributes for the plugin are set up using the standard ATTRS property. For this example, we will add an attribute called section that represents which part of the module (e.g. "header", "body", or "footer") will be updated with the returned content.

/*
 * The Standard Module section to which the io plugin instance is bound.
 * Response data will be used to populate this section, after passing through
 * the configured formatter.
 */
ATTRS: {
    section: {
        value:StdMod.BODY,
        validator: function(val) {
            return (!val || val == StdMod.BODY
                         || val == StdMod.HEADER
                         || val == StdMod.FOOTER);
        }
    }
}
};

Lifecycle Methods: initializer, destructor

The base WidgetIO plugin implements the initializer and destructor lifecycle methods. For the purposes of this example, we will extend the StdModIO plugin's initializer so that it activates the Flash based XDR transport so that the plugin is able to dispatch both in-domain and cross-domain requests (the transport used for any particular uri is controlled through the plugin's cfg attribute).

initializer: function() {
    // We setup a flag, so that we know if
    // flash is available to make the
    // XDR request.
    Y.on('io:xdrReady', function() {
        transportAvailable = true;
    });

    Y.io.transport({
        id:'flash',
        yid: Y.id,
        src:'../../build/io-xdr/io.swf?stamp=' + (new Date()).getTime()
    });
}

Using the Plugin

All objects derived from Base are Plugin Hosts. They provide plug and unplug methods to allow users to add/remove plugins to/from existing instances. They also allow the user to specify the set of plugins to be applied to a new instance, along with their configurations, as part of the constructor arguments.

In this example, we'll create a new instance of an Overlay:

/* Create a new Overlay instance, with content generated from script */
var overlay = new Y.Overlay({
    width:"40em",
    visible:false,
    align: {
        node:"#show",
        points: [Y.WidgetPositionAlign.TL, Y.WidgetPositionAlign.BL]
    },
    zIndex:10,
    headerContent: generateHeaderMarkup(),
    bodyContent: "Feed data will be displayed here"
});

And then use the plug method to add the StdModIO, providing it with a configuration to use when sending out io transactions (The Animation Plugin example shows how you could do the same thing during construction):

/*
 * Add the Standard Module IO Plugin, and configure it to use flash,
 * and a formatter specific to the pipes response we're expecting
 * from the uri request we'll send out.
 */
overlay.plug(StdModIO, {
    uri : pipes.baseUri + pipes.feeds["ynews"].uri,
    cfg:{
        xdr: {
            use:'flash'
        }
    },
    formatter: pipes.formatter,
    loading: '<img class="yui3-loading" width="32px" height="32px" src="../assets/overlay/img/ajax-loader.gif">'
});

For this example, the io plugin is configured to use the flash cross-domain transport, to send out requests to the pipes API for the feed the user selects from the dropdown.

Getting Feed Data Through Pipes

We setup an object (pipes) to hold the feed URIs, which can be looked up and passed to the plugin to dispatch requests for new data:

/* The Pipes feed URIs to be used to dispatch io transactions */

var pipes = {
    baseUri : 'http:/'+'/pipes.yahooapis.com/pipes/pipe.run? \
               _id=6b7b2c6a32f5a12e7259c36967052387& \
               _render=json&url=http:/'+'/',
    feeds : {
        ynews : {
            title: 'Yahoo! US News',
            uri: 'rss.news.yahoo.com/rss/us'
        },
        yui : {
            title: 'YUI Blog',
            uri: 'feeds.yuiblog.com/YahooUserInterfaceBlog'
        },
        slashdot : {
            title: 'Slashdot',
            uri: 'rss.slashdot.org/Slashdot/slashdot'
        },
        ...
    },

    ...

The data structure also holds the default formatter (pipes.formatter) required to convert the JSON responses from the above URIs to HTML. The JSON utility is first used to parse the json response string. The resulting object is iterated around, using Y.each(), and Y.Lang.sub() is used to generate the list markup:

...

// The default formatter, responsible for converting the JSON responses received,
// into HTML. JSON is used for the parsing step, and substitute for some basic
// templating functionality

formatter : function (val) {
    var formatted = "Error parsing feed data";
    try {
        var json = Y.JSON.parse(val);
        if (json && json.count) {
            var html = ['<ul class="yui3-feed-data">'];
            var linkTemplate =
                '<li><a href="{link}" target="_blank">{title}</a></li>';

            // Loop around all the items returned, and feed
            // them into the template above, using substitution.
            Y.each(json.value.items, function(v, i) {
                if (i < 10) {
                    html.push(Y.Lang.sub(linkTemplate, v));
                }
            });
            html.push("</ul>");
            formatted = html.join("");
        } else {
            formatted = "No Data Available";
        }
    } catch(e) {
        formatted = "Error parsing feed data";
    }
    return formatted;
}

The change handler for the select dropdown binds everything together, taking the currently selected feed, constructing the URI for the feed, setting it on the plugin, and sending out the request:

/* Handle select change */
Y.on("change", function(e) {
    var val = this.get("value");
    if (transportAvailable) {
        if (val != -1) {
            overlay.io.set("uri", pipes.baseUri + pipes.feeds[val].uri);
            overlay.io.refresh();
        }
    } else {
        overlay.io.setHTML("Flash doesn't appear to be available. Cross-domain requests to pipes cannot be made without it.");
    }
}, "#feedSelector");

Complete Example Source

<button type="button" id="show">Show Overlay</button>
<button type="button" id="hide">Hide Overlay</button>

<script type="text/javascript">
YUI().use("overlay", "json", "gallery-widget-io", "escape", function(Y) {

    /* Setup local variable for Y.WidgetStdMod, since we use it multiple times */
    var StdMod = Y.WidgetStdMod,
        transportAvailable = false;

    StdModIO = function(config) {
        StdModIO.superclass.constructor.apply(this, arguments);
    };

    Y.extend(StdModIO, Y.Plugin.WidgetIO, {
        initializer: function() {
            Y.on('io:xdrReady', function() {
                transportAvailable = true;
            });

            Y.io.transport({
                id:'flash',
                yid: Y.id,
                src:'../../build/io-xdr/io.swf?stamp=' + (new Date()).getTime()
            });
        },

        setHTML: function(content) {
            var overlay = this.get('host');
            overlay.setStdModContent(this.get('section'), content);
        }

    }, {
        NAME: 'stdModIO',
        NS: 'io',
        ATTRS: {
            section: {
                value:StdMod.BODY,
                validator: function(val) {
                    return (!val || val == StdMod.BODY || val == StdMod.HEADER || val == StdMod.FOOTER);
                }
            }
        }
    });

    /* The Pipes feed URIs to be used to dispatch io transactions */
    var pipes = {

        // uri data
        baseUri : 'http:/'+'/pipes.yahooapis.com/pipes/pipe.run?_id=6b7b2c6a32f5a12e7259c36967052387&_render=json&url=http:/'+'/',
        feeds : {
            ynews : {
                title: 'Yahoo! US News',
                uri: 'rss.news.yahoo.com/rss/us'
            },
            yui : {
                title: 'YUI Blog',
                uri: 'feeds.yuiblog.com/YahooUserInterfaceBlog'
            },
            slashdot : {
                title: 'Slashdot',
                uri: 'rss.slashdot.org/Slashdot/slashdot'
            },
            ajaxian: {
                title: 'Ajaxian',
                uri: 'feeds.feedburner.com/ajaxian'
            },
            daringfireball: {
                title: 'Daring Fireball',
                uri: 'daringfireball.net/index.xml'
            },
            wiredtech: {
                title: 'Wire: Tech Biz',
                uri: 'www.wired.com/rss/techbiz.xml'
            },
            techcrunch: {
                title: 'TechCrunch',
                uri: 'feedproxy.google.com/Techcrunch'
            }
        },

        // The default formatter, responsible for converting the JSON responses recieved,
        // into HTML, using JSON for the parsing step, and substitute for some basic templating functionality
        formatter : function (val) {
            var formatted = "Error parsing feed data";
            try {
                var json = Y.JSON.parse(val);
                if (json && json.count) {
                    var html = ['<ul class="yui3-feed-data">'];
                    var linkTemplate = '<li><a href="{link}" target="_blank">{title}</a></li>';

                    Y.each(json.value.items, function(v, i) {
                        if (i < 10) {
                            v.title = Y.Escape.html(v.title);
                            v.link = Y.Escape.html(v.link);
                            html.push(Y.Lang.sub(linkTemplate, v));
                        }
                    });
                    html.push("</ul>");
                    formatted = html.join("");
                } else {
                    formatted = "No Data Available";
                }
            } catch(e) {
                formatted = "Error parsing feed data";
            }
            return formatted;
        }
    };

    /* Helper function, to generate the select dropdown markup from the pipes feed data */
    function generateHeaderMarkup() {
        var optTemplate = '<option value="{id}">{title}</option>',
            html = ['<select id="feedSelector" class="yui3-feed-selector"><option value="-1" class="yui3-prompt">Select a Feed...</option>'];

        Y.Object.each(pipes.feeds, function(v, k, o) {
            html.push(Y.Lang.sub(optTemplate, {id:k, title:v.title}));
        });
        html.push('</select>');

        return html.join("");
    }

    /* Create a new Overlay instance, with content generated from script */
    var overlay = new Y.Overlay({
        width:"40em",
        visible:false,
        align: {
            node:"#show",
            points: [Y.WidgetPositionAlign.TL, Y.WidgetPositionAlign.BL]
        },
        zIndex:10,
        headerContent: generateHeaderMarkup(),
        bodyContent: "Feed data will be displayed here"
    });

    overlay.render();
    /*
     * Add the Standard Module IO Plugin, and configure it to use flash, and a formatter specific
     * to the pipes response we're expecting from the uri request we'll send out.
     */
    overlay.plug(StdModIO, {
        uri : pipes.baseUri + pipes.feeds["ynews"].uri,
        cfg:{
            xdr: {
                use:'flash'
            }
        },
        formatter: pipes.formatter,
        loading: '<img class="yui3-loading" width="32px" height="32px" src="../assets/overlay/img/ajax-loader.gif">'
    });

    Y.on("change", function(e) {
        var val = this.get("value");
        if (transportAvailable) {
            if (val != -1) {
                overlay.io.set("uri", pipes.baseUri + pipes.feeds[val].uri);
                overlay.io.refresh();
            }
        } else {
            overlay.io.setHTML("Flash doesn't appear to be available. Cross-domain requests to pipes cannot be made without it.");
        }
    }, "#feedSelector");

    Y.on("click", function(e) {
        overlay.show();
    }, "#show");

    Y.on("click", function(e) {
        overlay.hide();
    }, "#hide");

});
</script>