(function ($) {
$.fn.extend({
onHtml: function (optUrl, optRequestData, optErrorCallback, optDebug) {
onhtml_assign_attr = function (obj, attributes) {
if (typeof attributes == 'object' && attributes != null) {
$.each(attributes, function (key, attr) {
$(obj).attr(key, attr);
});
}
}
onhtml_assign_events = function (obj, events) {
if (typeof events == 'object' && events != null) {
$.each(events, function (key, func) {
if (typeof window[key] == 'function') {
$(obj).bind(key, window[func]);
}
});
}
}
onhtml_assign_css = function (obj, css) {
if (typeof css == 'object' && css != null) {
$.each(css, function (key, prop) {
$(obj).css(key, prop);
});
}
}
onhtml_handle_callback = function (callback) {
if (typeof callback == 'object' && callback != null) {
$.each(callback, function (key, args) {
if (typeof window[key] == 'function') {
window[key](args);
}
});
}
}
onhtml_make = function (data) {
var dom = document.createElement(data.tag);
$.each(data.html, function (key, val) {
if (typeof val.html == 'object' && val.html != null) {
content = onhtml_make(val);
} else {
content = document.createElement(val.tag);
$(content).html(val.html);
}
handle_element_load(content, val);
$(dom).append(content);
});
return dom;
}
handle_element_load = function (content, data) {
onhtml_assign_attr(content, data.attributes);
onhtml_handle_callback(data.callback);
onhtml_assign_events(content, data.events);
onhtml_assign_css(content, data.css)
}
return this.each(function () {
var obj = $(this);
var url = '';
if (optUrl == null && (typeof obj.attr('data-onhtml') == 'undefined' || obj.attr('data-onhtml') == null)) {
return;
} else {
if (typeof obj.attr('data-onhtml') != 'undefined') {
url = obj.attr('data-onhtml');
} else {
url = optUrl;
}
}
$.getJSON(url, optRequestData , function (data) {
var start = new Date().getMilliseconds();
$(obj).html('');
if (typeof data.error == 'object') {
window[error_handler](data);
}
if (typeof data.html == 'object' && data.html != null) {
content = onhtml_make(data);
} else {
content = document.createElement(data.tag);
$(content).html(data.html);
}
handle_element_load(content, data);
$(obj).append(content);
var stop = new Date().getMilliseconds();
var executionTime = stop - start;
alert('Render time: ' + executionTime+"ms");
}).error(function (xhr, ajaxOptions, thrownError) {
if (optDebug) {
alert(thrownError + ' \n\nResponse:\n\n' + xhr.responseText);
}
if (typeof optErrorCallback == 'function') {
options.errorCallback.call(obj, xhr);
}
});
});
}
});
})(jQuery);
|