📜 ⬆️ ⬇️

'Clean' javascript: "Continuation"

Sometimes humanity is striking in its stupidity and unwillingness to see the situation as it really is ... (Unknown)

Perhaps this epigraph has more to do with me than I think, but I would like to hope for the best ...

My first post turned out, to put it mildly, not very, but anyone should be able to fix everything and now I will try to use it.
')
I'll tell you a little story that happened to me at work. It was a long time ago, somehow I was attached to a new web-project, the design of which I had no relation to. Timlid first of all filled in svn php and js framework.
Mootools 1.2.2 or 1.2.4 was chosen as JS, and in addition to it Jx UI Library as JxLib . Everything went well, the project was coming to an end, browser versions grew and so on. And so, one fine day, when I came to work, I saw a bug, the bark said that the admin in IE9 (and it just came out) does not work at all. The first things I started looking for a problem, as it turned out, Mootools 1.2.x - does not support IE9, but in versions over 1.3.x - everything works and flies. Well, for a long time without thinking, download the latest version of this miracle and set. Were not happy for a long time - they started climbing bugs in JxLib . It turns out that the project is 'stalled', and the latest available version is only compatible with Mootools 1.2.x. Much time has passed since that moment, but the shit code with which this bug had to be patched broke my faith in Mootools and similar things. Now, I think it has become clear where this attitude to JS libs come from.

And now I want to answer (explain why so, and not otherwise) to some comments.

one)
Console.log - I did not expect this, I offered a lot, but not this. I am aware of the fact that it (console.log) supports formatting and transferring several parameters, but I cannot remember the last time I used it. One variable is enough for me, and complicating _d () in order to use the full power of console.log once a month is impractical (it is easier to write the cherished 11 characters `console.log`).

2)
The addEvent function will continue to execute after handling the error using the _d function.
- I am aware of this, this is done on purpose, because I check for the existence of a DOM object, but I prefer to do it in the main script, but you convinced me - I’ll add return false.

3)
Pollution of the global variable space is a very bad tone.
- here you are right, but except for readyList = []; I can not find anything global :)

Well, I think it's time to finish these holivars and start considering the new batch of JS code.


//       -  3  (        )     /** * Function insert DOM element before some element * * @version 2012-11-06 * @param Object new_element * @param Object targetElement * @return void */ function insertBefore(new_element, targetElement) { targetElement.parentNode.insertBefore(new_element, targetElement); } /** * Function insert DOM element after some element * * @version 2012-11-06 * @param Object new_element * @param Object targetElement * @return void */ function insertAfter(new_element, targetElement) { var parent = targetElement.parentNode; //if the parents lastchild is the targetElement... if(parent.lastchild == targetElement) parent.appendChild(new_element); else parent.insertBefore(new_element, targetElement.nextSibling); } /** * Function make clone of income object * * @version 2012-11-07 * @param Object obj * @return Object */ function clone(obj) { if(obj == null || typeof(obj) != 'object') return obj; var temp = {}; for(var key in obj) temp[key] = clone(obj[key]); return temp; } //    DOM   ,    /** * Function return next element in dom object * * @version 2013-01-08 * @param Object obj * @return Object */ function getNext(obj) { obj = obj.nextSibling; if(!obj) return false; while(obj.nodeType != 1){ obj = obj.nextSibling; if(!obj) return false; } return obj; } //    DOM   ,    /** * Function return previous element in dom object * * @version 2013-02-13 * @param Object obj * @return Object */ function getPrevious(obj) { obj = obj.previousSibling; if(!obj) return false; while(obj.nodeType != 1){ obj = obj.previousSibling; if(!obj) return false; } return obj; } //  2  -     Cookies. C ,  ,    /** * Function new Cookies * * @version 2013-03-26 * @param string name * @param string value * @param string expires * @param string path * @return void */ function setCookies(name, value, expires, path) { if(!name || !value) return 0; if(!expires){ expires = new Date(); expires.setTime(expires.getTime() + (1000 * 86400 * 365)); //save 1 year } if(!path) path = '/'; // set Cookies document.cookie = name+'='+escape(value)+'; expires='+expires.toGMTString()+'; path='+path; } /** * Function return Cookies value by name * * @version 2013-03-26 * @param string name * @return void */ function getCookies(name) { var results = document.cookie.match ( '(^|;) ?' + name + '=([^;]*)(;|$)' ); if ( results ) return ( unescape ( results[2] ) ); else return null; } //      //    Ajax(params),      prototype /** * Ajax object * * Send request by post/get to some url * * @version 2013-02-13 * @param Object params * @return Object */ window.Ajax = function(params) { //    this.options = { // default url url: '', // default method method: 'get', // Is synchronous request? async: true, // in seconds timeout: 10000, // callback function, in default - empty function onComplete: function(){} }; // set config params this.setConfig(params); //     XMLHttpRequest    // initialize this.init(params); }; /** * Pablic methods */ window.Ajax.prototype = { /** * some internal params */ xml_http_request: null, timeout: null, // json|xml|text response:'json', //   ajax ,     /** * configure functionality */ setConfig: function(opt) { // set url if(opt.url != undefined) this.options.url = opt.url; // set method if(opt.method != undefined) this.options.method = opt.method; // set asynchronus param if(opt.async != undefined) this.options.async = opt.async; // set timeout if(opt.timeout != undefined) this.options.timeout = opt.timeout; // set callback functions if((opt.onComplete != undefined) && (typeof(opt.onComplete) == 'function')) this.options.onComplete = opt.onComplete; }, /** * Initialize XMLHTTPRequest */ init: function() { //   XMLHttpRequest // Cross-browser compatibility for browsers if (typeof XMLHttpRequest != 'undefined') { this.xml_http_request = new XMLHttpRequest(); } else{ try { this.xml_http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { this.xml_http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { alert('Your browser don\'t support Ajax technology. Please download real browser :)'); } } } var self_ = this; //   (post/get), url, /  // open XMLHttpRequest this.xml_http_request.open(self_.options.method, self_.options.url, self_.options.async); /**  callback    * *   readyState : * 0 - Unitialized * 1 - Loading * 2 - Loaded * 3 - Interactive * 4 - Complete *  0-2   . * * self_.xml_http_request.status -    (200, 404  ) */ // set callback function for XMLHttpRequest this.xml_http_request.onreadystatechange = function(){ if((self_.xml_http_request.readyState == 4) && (self_.xml_http_request.status > 0)){ //    Ajax  (  ) // delete timeout clearTimeout(self_.timeout); //    ,       // JSON.parse -   JSON (  - bye-bye) if(self_.response == 'json') var response = JSON.parse(self_.xml_http_request.responseText); else{ if(self_.response == 'xml') var response = self_.xml_http_request.responseXML; else var response = self_.xml_http_request.responseText; } //    self_.options.onComplete(response); } } }, //       ,        /** * Set some headers if need */ setRequestHeader: function(name, value) { this.xml_http_request.setRequestHeader(name, value); }, //  Ajax   /** * Send request */ send: function(params) { this.xml_http_request.send(params); var self_ = this; //     ,         -    //   - 10  ,     // set timeout need for abort request this.timeout = setTimeout( function(){ self_.xml_http_request.abort(); }, this.options.timeout); }, //    ,         ,     (     :) ) /** * Abort request */ abort: function() { this.xml_http_request.abort(); } }   Ajax(): new Ajax({ url: '/index.php', timeout: 20000, method: 'post', onComplete: function(data){ alert(data);} }).send('qwerty=123'); 


Ps. As promised, the source . The article was written so that people would not forget true JavaScript and go over to the bright side of power (there are also cookies here :)).

Source: https://habr.com/ru/post/176273/


All Articles