Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created December 7, 2011 20:15
Show Gist options
  • Save kara-ryli/1444436 to your computer and use it in GitHub Desktop.
Save kara-ryli/1444436 to your computer and use it in GitHub Desktop.
Spun off from widget-functions this is a big time saver when building DOM in Y.Widget
YUI.add("widget-node-builder", function (Y) {
/**
* Extension enabling a Widget to easily build DOM.
*
* @module widget-node-builder
*/
var yNodeCreate = Y.Node.create,
yObjectEach = Y.Object.each,
yLangIsFunction = Y.Lang.isFunction;
function nodeSetAttrs(value, key) {
this.setAttribute(key, value);
}
/**
* Widget extension providing functionality enabling a Widget to build
* internal DOM.
*
* @class WidgetNodeBuilder
* @constructor
* @uses Node
*/
function WidgetNodeBuilder() {}
/**
* @method buildNode
* @param config {Object} An configuration object defining the node. Valid options:
* <ul>
* <li><b>template</b>: The DOM element to create. Defaults to <code>"<div></div>"</code>.</li>
* <li><b>className</b>: A value for the <code>class</code> attribute. Uses the host's
* <code>getClassName</code> method if available.</li>
* <li><b>attrs</b>: An object dictionary of attributes to add to the node
* using <code>setAttribute</code>.</li>
* <li><b>content</b>: Content to add to the node using <code>setContent</code>.</li>
* </ul>
* @description Creates a Node with the provided configuration options.
* @return {Node} Y.Node wrapping the created DOM.
*/
WidgetNodeBuilder.prototype.buildNode = function (config) {
var cfg = config || {},
node = yNodeCreate(cfg.template || "<div></div>");
if (cfg.className) {
node.addClass(yLangIsFunction(this.getClassName) ? this.getClassName(cfg.className) : cfg.className);
}
if (cfg.attrs) {
yObjectEach(cfg.attrs, nodeSetAttrs, node);
}
if (cfg.content) {
node.setContent(cfg.content);
}
return node;
};
Y.WidgetNodeBuilder = WidgetNodeBuilder;
}, "3.4.1", { requires: ["node-base"] });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment