[jQuery] Making $.metadata extensible
I've been playing with the metadata plugin but like the idea of
migrating to HTML5, including the data- attributes for metadata. I
realized that rather than constantly rewriting the plugin with new
methods, the plugin itself should be extensible. Thus, instead of the
monolithic $.metadata.get, use:
$.metadata.get = function( elem, opts ){
var opts = $.extend({},this.defaults,opts);
return $.data(elem, opts.single) || $.data(elem, opts.single,
this[opts.type](elem, opts));
};
and define all the techniques for getting the data from an element
that you want:
// the original methods
$.extend($.metadata,{
"class": function (elem, opts){
var m = opts.cre.exec( elem.className );
if ( m ) return eval('('+m[1]+')');
return {};
},
elem: function (elem, opts){
var e = elem.getElementsByTagName(opts.name);
if ( e.length ) return eval('('+e[0].innerHTML+')');
return {};
},
attr: function (elem, opts){
var attr = elem.getAttribute( opts.name );
// allow for not including the braces, as in the original metadata
if ( attr ){
if ( attr.indexOf( '{' ) <0 ) attr = "{" + attr + "}";
return eval('('+attr+')');
}
return {};
}
}
// based on Andrea Ercolino's metaobjects (http://noteslog.com/
metaobjects/)
$.metadata.object = function (elem, opts){
var ret = {};
$('> object.metaobject > param', elem).each(function(){
ret[this.name] = eval('('+this.value+')');
});
return ret;
};
// HTML5 compliant-my favorite (http://www.w3.org/html/wg/html5/
#custom)
$.metadata.data = function (elem, opts){
var ret = {};
$.each (elem.attributes, function(){
var m = /data-(.*)/.exec(this.nodeName);
if (m) ret[m[1]] = eval('('+this.nodeValue+')');
});
return ret;
}
Any thoughts from people who use metadata?