Skip to main content
Shortened title; removed noise
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

I'm working on my own JS-lib and I need someone to help. Basic JavaScript library

My own CMS is currently using J-QueryjQuery, but as one of the goals is to have the whole project to be very small, so I've decided to write my own basic library, I. I only really need to select elements and modify them using results from my server. (via AJaxAjax).

###The Javascript-library v0.01: (Attempt 1) (function(){ a=this.Function; a.prototype.extend=(function(a,b){this[a]=b;return this}); a.prototype.implement=(function(a,b){this.prototype[a]=b;return this}); $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)}) .extend("post",(function(a,b){ c=[]; for(x in a) c[c.length]=[x,a[x]].join("="); d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); d.open("POST","./",true); d.setRequestHeader("Content-type","application/x-www-form-urlencoded"); d.onreadystatechange=b; d.send(c.join("&")); return this; })) .extend("each",(function(a,b,c){ for(x in a) if(a.hasOwnProperty(x)) b.call(c, a[x], x, a); return this; })); })();The JavaScript-library v0.01: (Attempt 1)

Okay I know that querySelectorAll can't be relied on, but it is just good for the start of this.

(function(){
    a=this.Function;
    a.prototype.extend=(function(a,b){this[a]=b;return this});
    a.prototype.implement=(function(a,b){this.prototype[a]=b;return this});
    $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)})
    .extend("post",(function(a,b){
        c=[];
        for(x in a)
            c[c.length]=[x,a[x]].join("=");
        d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        d.open("POST","./",true);
        d.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        d.onreadystatechange=b;
        d.send(c.join("&"));
        return this;
    }))
    .extend("each",(function(a,b,c){
        for(x in a)
            if(a.hasOwnProperty(x))
                b.call(c, a[x], x, a);
        return this;
    }));
})();

###So what is the point on why I posted this? Simpleknow that querySelectorAll can't be relied on, thisbut it is code-review and I need feedback, Thanks to anyone withjust good for the commentsstart of this.

###The Javascript-library v0.02: (Attempt 2) OkayThe JavaScript-library v0.02: (Attempt 2)

I believe this is heapsmuch improved (I think) it. It has reasonable variable names, works better, and most of all is quite buggy. :( Any ideas?

I'm working on my own JS-lib and I need someone to help.

My own CMS is currently using J-Query but as one of the goals is to have the whole project to be very small, so I've decided to write my own basic library, I only really need to select elements and modify them using results from my server. (via AJax)

###The Javascript-library v0.01: (Attempt 1) (function(){ a=this.Function; a.prototype.extend=(function(a,b){this[a]=b;return this}); a.prototype.implement=(function(a,b){this.prototype[a]=b;return this}); $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)}) .extend("post",(function(a,b){ c=[]; for(x in a) c[c.length]=[x,a[x]].join("="); d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); d.open("POST","./",true); d.setRequestHeader("Content-type","application/x-www-form-urlencoded"); d.onreadystatechange=b; d.send(c.join("&")); return this; })) .extend("each",(function(a,b,c){ for(x in a) if(a.hasOwnProperty(x)) b.call(c, a[x], x, a); return this; })); })();

Okay I know that querySelectorAll can't be relied on, but it is just good for the start of this.

###So what is the point on why I posted this? Simple, this is code-review and I need feedback, Thanks to anyone with the comments.

###The Javascript-library v0.02: (Attempt 2) Okay this is heaps improved (I think) it has reasonable variable names, works better, and most of all is quite buggy. :( Any ideas?

Basic JavaScript library

My own CMS is currently using jQuery, but as one of the goals is to have the whole project to be very small, I've decided to write my own basic library. I only really need to select elements and modify them using results from my server (via Ajax).

The JavaScript-library v0.01: (Attempt 1)

(function(){
    a=this.Function;
    a.prototype.extend=(function(a,b){this[a]=b;return this});
    a.prototype.implement=(function(a,b){this.prototype[a]=b;return this});
    $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)})
    .extend("post",(function(a,b){
        c=[];
        for(x in a)
            c[c.length]=[x,a[x]].join("=");
        d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        d.open("POST","./",true);
        d.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        d.onreadystatechange=b;
        d.send(c.join("&"));
        return this;
    }))
    .extend("each",(function(a,b,c){
        for(x in a)
            if(a.hasOwnProperty(x))
                b.call(c, a[x], x, a);
        return this;
    }));
})();

I know that querySelectorAll can't be relied on, but it is just good for the start of this.

The JavaScript-library v0.02: (Attempt 2)

I believe this is much improved. It has reasonable variable names, works better, and most of all is quite buggy.

Added attempt 2.
Source Link

###The Javascript-library so farv0.01: (Attempt 1) (function(){ a=this.Function; a.prototype.extend=(function(a,b){this[a]=b;return this}); a.prototype.implement=(function(a,b){this.prototype[a]=b;return this}); $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)}) .extend("post",(function(a,b){ c=[]; for(x in a) c[c.length]=[x,a[x]].join("="); d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); d.open("POST","./",true); d.setRequestHeader("Content-type","application/x-www-form-urlencoded"); d.onreadystatechange=b; d.send(c.join("&")); return this; })) .extend("each",(function(a,b,c){ for(x in a) if(a.hasOwnProperty(x)) b.call(c, a[x], x, a); return this; })); })();

###Edit###The Javascript-library v0.02: Updated code(Attempt 2) Okay this is heaps improved (I think) it has reasonable variable names, Thanks to allworks better, This codeand most of all is cleaned version from @IvoWetzel;quite buggy. :( Any ideas?

(var _    = new function Sample(){};  ////////////////////////////////////////
    _.temp  = {};                    // This Object is intended just for
    _.pages = {};                    // testing, I do the rest in the console
    _.pid   = {};                    // <- Stores the current pageID
    _.el    = {};                    // /PAGE-ID/PAGE-TITLE or #!page=PAGE-ID
    _.fn    = {};                    ////////////////////////////////////////
    _.$    = {};                     // <- Lets leave JQuery alown. :)
(function(){
    this.$ = function(selectora, parentSelectorb, indexc) {
        varif(b&&b.isType("string")) element = parentSelectorb ?= $(parentSelectorb)[index;
 || 0] :     d=b?b[c|0]:document;
        return elementdocument.querySelectorAllgetElementsByClassName.call(selectord,a);
    };
    $var $FP = Function.extendprototype, $OP = Object.prototype;
    $OP.isType = function (obj, propstype){
        return typeof this === type;
    }
    $OP.each   = function(fun){ // `fun()` runs 3 times HOW??
        forif(this.isType("array")&&this.forEach) return this.forEach(a); // if this is an array and we have a browser with Array().forEach then lets use native code instead.
        if(this.isType("object")||this.isType("array"))
            for(var ix in propsthis)
            if    if(propsthis.hasOwnProperty(ix))
                obj[i] = props[i];  fun.call(this[x],x,this);
        return this;
    };
    $$OP.extend($,toString    = function(){
        post:if(!this.isType("object")&&!this.isType("array")) functionreturn this;
        var arr=[];
        this.each(data,function(a){
 callback           arr[arr.length] = a+"="+this;
        });
 {       return arr.join("&");
    }
    $FP.multiInput = $FP.MI   = function(){
        var paramsself = [];this;
        return function(obj){
     for       if(varobj.isType("object")||obj.isType("array"))
 i in data             obj.each(function(a,b){
                if (data   self.hasOwnPropertycall(ib,a,this);
                });
            else
         params       self.pushapply([ithis,arguments);
 data[i]]           return this;
        };
    };
    $OP.joinextend = function('='key,val){ // I want to add all my functions dynamicly and in bulk.
        (this.prototype||this)[key]=val; // Either myObject.extend("key","val") or my Object.extend({"key":"val"}) work.
        return this;
    }.MI(); // MI/multiInput simply allows objects to be passed instead of making it more sence to use obj.prototype.test=myvalue;
    this.$.extend({
        "post": function(a,b,c,d){
            var req=XMLHttpRequeste=XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            reqe.open('post'"post", '/'a, true);
            reqe.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            reqe.onreadstatechange = callback;function(){
            req    if(xmlhttp.readyState==4) // Page has fully loaded, now did we get a status code of "200 ok" or an error? Please tell me if "304 Not modified" should be added as run `c` and not `d`
                    (xmlhttp.status==200?c:d).call(xmlhttp.responseText,xmlhttp);
            };
            e.send(paramsb.jointoString('&'));
            return this;
        },
        each"post_json": function (obja, funcb, thatc) {
            forreturn this.post(var i in obja,b,function(){
                if c.call(obj"return "+$.hasOwnPropertyFunction(ithis)()
    ); // This should run c with this being the object. What works better `()` or func`.call(that, obj[i],)` obj,?? i);
            return this;});
        }
    });
 }).call(_); // Lets window.$Leave =JQuery $;alown.
}
_.$.prototype.each(function(){console.log(this)});

###The Javascript-library so far: (function(){ a=this.Function; a.prototype.extend=(function(a,b){this[a]=b;return this}); a.prototype.implement=(function(a,b){this.prototype[a]=b;return this}); $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)}) .extend("post",(function(a,b){ c=[]; for(x in a) c[c.length]=[x,a[x]].join("="); d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); d.open("POST","./",true); d.setRequestHeader("Content-type","application/x-www-form-urlencoded"); d.onreadystatechange=b; d.send(c.join("&")); return this; })) .extend("each",(function(a,b,c){ for(x in a) if(a.hasOwnProperty(x)) b.call(c, a[x], x, a); return this; })); })();

###Edit: Updated code, Thanks to all, This code is cleaned version from @IvoWetzel;

(function () {
    function $(selector, parentSelector, index) {
        var element = parentSelector ? $(parentSelector)[index || 0] : document;
        return element.querySelectorAll(selector);
    };
    $.extend = function (obj, props) {
        for (var i in props)
            if (props.hasOwnProperty(i))
                obj[i] = props[i];
        return this;
    };
    $.extend($, {
        post: function (data, callback) {
            var params = [];
            for (var i in data)
                if (data.hasOwnProperty(i))
                    params.push([i, data[i]].join('='));
            var req=XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            req.open('post', '/', true);
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.onreadstatechange = callback;
            req.send(params.join('&'));
            return this;
        },
        each: function (obj, func, that) {
            for (var i in obj)
                if (obj.hasOwnProperty(i))
                    func.call(that, obj[i], obj, i);
            return this;
        }
    });
    window.$ = $;
})();

###The Javascript-library v0.01: (Attempt 1) (function(){ a=this.Function; a.prototype.extend=(function(a,b){this[a]=b;return this}); a.prototype.implement=(function(a,b){this.prototype[a]=b;return this}); $=(function(a,b,c){return (b?$(b)[c?c:0]:document).querySelectorAll(a)}) .extend("post",(function(a,b){ c=[]; for(x in a) c[c.length]=[x,a[x]].join("="); d=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); d.open("POST","./",true); d.setRequestHeader("Content-type","application/x-www-form-urlencoded"); d.onreadystatechange=b; d.send(c.join("&")); return this; })) .extend("each",(function(a,b,c){ for(x in a) if(a.hasOwnProperty(x)) b.call(c, a[x], x, a); return this; })); })();

###The Javascript-library v0.02: (Attempt 2) Okay this is heaps improved (I think) it has reasonable variable names, works better, and most of all is quite buggy. :( Any ideas?

var _    = new function Sample(){};  ////////////////////////////////////////
    _.temp  = {};                    // This Object is intended just for
    _.pages = {};                    // testing, I do the rest in the console
    _.pid   = {};                    // <- Stores the current pageID
    _.el    = {};                    // /PAGE-ID/PAGE-TITLE or #!page=PAGE-ID
    _.fn    = {};                    ////////////////////////////////////////
    _.$    = {};                     // <- Lets leave JQuery alown. :)
(function(){
    this.$ = function(a,b,c){
        if(b&&b.isType("string"))   b = $(b);
        d=b?b[c|0]:document;
        return document.getElementsByClassName.call(d,a);
    };
    var $FP = Function.prototype, $OP = Object.prototype;
    $OP.isType = function (type){
        return typeof this === type;
    }
    $OP.each   = function(fun){ // `fun()` runs 3 times HOW??
        if(this.isType("array")&&this.forEach) return this.forEach(a); // if this is an array and we have a browser with Array().forEach then lets use native code instead.
        if(this.isType("object")||this.isType("array"))
            for(var x in this)
                if(this.hasOwnProperty(x))
                    fun.call(this[x],x,this);
        return this;
    };
    $OP.toString    = function(){
        if(!this.isType("object")&&!this.isType("array")) return this;
        var arr=[];
        this.each(function(a){
            arr[arr.length] = a+"="+this;
        });
        return arr.join("&");
    }
    $FP.multiInput = $FP.MI   = function(){
        var self = this;
        return function(obj){
            if(obj.isType("object")||obj.isType("array"))
                obj.each(function(a,b){
                    self.call(b,a,this);
                });
            else
                self.apply(this,arguments);
            return this;
        };
    };
    $OP.extend = function(key,val){ // I want to add all my functions dynamicly and in bulk.
        (this.prototype||this)[key]=val; // Either myObject.extend("key","val") or my Object.extend({"key":"val"}) work.
        return this;
    }.MI(); // MI/multiInput simply allows objects to be passed instead of making it more sence to use obj.prototype.test=myvalue;
    this.$.extend({
        "post": function(a,b,c,d){
            var e=XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        e.open("post", a, true);
            e.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            e.onreadstatechange = function(){
                if(xmlhttp.readyState==4) // Page has fully loaded, now did we get a status code of "200 ok" or an error? Please tell me if "304 Not modified" should be added as run `c` and not `d`
                    (xmlhttp.status==200?c:d).call(xmlhttp.responseText,xmlhttp);
            };
            e.send(b.toString());
            return this;
        },
        "post_json": function(a,b,c){
            return this.post(a,b,function(){
                c.call("return "+$.Function(this)()); // This should run c with this being the object. What works better `()` or `.call()` ?? 
            });
        }
    });
}).call(_); // Lets Leave JQuery alown.

_.$.prototype.each(function(){console.log(this)});
Improved formatting. Added in updates.
Source Link

###Edit: Updated code, Thanks to all, This code is cleaned version from @IvoWetzel;

(function () {
    function $(selector, parentSelector, index) {
        var element = parentSelector ? $(parentSelector)[index || 0] : document;
        return element.querySelectorAll(selector);
    };
    $.extend = function (obj, props) {
        for (var i in props)
            if (props.hasOwnProperty(i))
                obj[i] = props[i];
        return this;
    };
    $.extend($, {
        post: function (data, callback) {
            var params = [];
            for (var i in data)
                if (data.hasOwnProperty(i))
                    params.push([i, data[i]].join('='));
            var req=XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            req.open('post', '/', true);
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.onreadstatechange = callback;
            req.send(params.join('&'));
            return this;
        },
        each: function (obj, func, that) {
            for (var i in obj)
                if (obj.hasOwnProperty(i))
                    func.call(that, obj[i], obj, i);
            return this;
        }
    });
    window.$ = $;
})();

###Edit: Updated code, Thanks to all, This code is cleaned version from @IvoWetzel;

(function () {
    function $(selector, parentSelector, index) {
        var element = parentSelector ? $(parentSelector)[index || 0] : document;
        return element.querySelectorAll(selector);
    };
    $.extend = function (obj, props) {
        for (var i in props)
            if (props.hasOwnProperty(i))
                obj[i] = props[i];
        return this;
    };
    $.extend($, {
        post: function (data, callback) {
            var params = [];
            for (var i in data)
                if (data.hasOwnProperty(i))
                    params.push([i, data[i]].join('='));
            var req=XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            req.open('post', '/', true);
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.onreadstatechange = callback;
            req.send(params.join('&'));
            return this;
        },
        each: function (obj, func, that) {
            for (var i in obj)
                if (obj.hasOwnProperty(i))
                    func.call(that, obj[i], obj, i);
            return this;
        }
    });
    window.$ = $;
})();
Tweeted twitter.com/#!/StackCodeReview/status/33176001420730368
added 135 characters in body
Source Link
Loading
Source Link
Loading