Browse Source

ajax.processTags, ajax.processTag

Volodymyr Tkach 2 years ago
parent
commit
aa7fbd4fcf
1 changed files with 66 additions and 0 deletions
  1. 66 0
      js/ajax.js

+ 66 - 0
js/ajax.js

@@ -86,3 +86,69 @@ ajax.post = function(url, data, callback, async) {
 	};
 	ajax.send(url, callback, 'POST', query.join('&'), async);
 };
+
+// TODO: rework later (remove duplicated code)
+ajax.hasClass = function(obj, className) {
+	return !!obj.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
+};
+
+ajax.addClass = function(obj, className) {
+	if(!ajax.hasClass(obj, className)) obj.className += " " + className;
+};
+
+ajax.removeClass = function(obj, className) {
+	if(ajax.hasClass(obj, className)) {
+		var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
+		obj.className = obj.className.replace(reg, ' ').trim();
+	};
+};
+
+ajax.processTag = function(tag, url, func) {
+	if(typeof window[func] === 'function') {
+		if(!ajax.hasClass(tag, 'loading')) {
+			ajax.addClass(tag, 'loading');
+			var body = document.getElementsByTagName('body');
+			if(body.length >= 1) { ajax.addClass(body[0], 'loading'); };
+			ajax.getJSON(url, {}, function(method, data, readyState, status, responseData) {
+				var body = document.getElementsByTagName('body');
+				if(body.length >= 1) { ajax.removeClass(body[0], 'loading'); };
+				try {
+					var resp = window[func](tag, responseData);
+					tag.innerHTML = resp;
+				} catch(e) {
+					console.log('ajax.processTag', 'e', e);
+				};
+				ajax.removeClass(tag, 'loading');
+			}, function(method, data, readyState, status, responseData) {
+				ajax.removeClass(tag, 'loading');
+				var body = document.getElementsByTagName('body');
+				if(body.length >= 1) { ajax.removeClass(body[0], 'loading'); };
+			});
+		};
+	};
+};
+
+ajax.processTags = function() {
+	var tags = document.querySelectorAll('[data-ajax-get]');
+	for(var key in tags) if(tags.hasOwnProperty(key)) {
+		var tag = tags[key];
+		var get = tag.getAttribute('data-ajax-get');
+		var func = tag.getAttribute('data-ajax-func');
+		var delay = tag.getAttribute('data-ajax-delay');
+		if(get && get != null && func && func != null) {
+			if(delay == null) {
+				ajax.processTag(tag, get, func);
+			} else {
+				setTimeout(function() {
+					ajax.processTag(tag, get, func);
+				}, delay);
+			};
+		};
+	};
+};
+
+if(window.attachEvent) {
+	window.attachEvent('onload', ajax.processTags);
+} else if(window.addEventListener) {
+	window.addEventListener('load', ajax.processTags, false);
+};