Programming

(JavaScript) How to make a cool $() selector

steloflute 2013. 4. 9. 23:30

https://coderwall.com/p/83eq8w


I know that %98 of times all you need is download jQuery, but you can learn some little things of how frameworks work making your own tiny-framework.

(This is my first write in english, don't blame on me)

Maybe you've learned that you can use functions that works as constructors and make new shiny instance objects. Something like this:

var Dog = function(options) {
    this.name = options.name;
    this.voice =  options.voice;
    return this;
};

var dogMaker = function(options) {
   return new Dog(options);
};

var myDog = dogMaker({
    name: "Tango",
    voice: "woof!"
});

And maybe you know, that the $ symbol is valid in JavaScript, and can be used as the name of any object:

var myToolbox = function(query) {
     var el = document.querySelectorAll(query),
         i;
     for(i = 0; i < el.length; i++) {
         this[i] = el[i];
     }
     this.length = i;
     return this;
}

var $ = function(query) {
    return new myToolbox(query);
}

Using this code you can create new objects from querySelectorAll queries, like $("body") $("#myDivId") $(".myClass").

The next step is to add some methods to the prototype of the instance objects, so will be available to all instances:

myToolbox.prototype = {
    show: function() {
        this[0].style.display = "block";
    },
    hide: function() {
        this[0].style.display = "none";
    }
}

And now you can do some interesting things like:

$("body").show();
$("body").hide();

If you write $("div").length, it will work and return the number of div elements on the document. Write only $("div") and you will see that the returned value is not an Array, but a myToolbox object. So if we want to workaround this and return an Array as the response, we can inherits Array's prototype:

$.prototype = myToolbox.prototype = [];

Here is the final code, enjoy it!

var myToolbox = function(query) {
     var el = document.querySelectorAll(query);
     for(i = 0; i < el.length; i++) {
         this[i] = el[i];
     }
     this.length = i;
     return this;
}

var $ = function(query) {
    return new myToolbox(query);
}

$.prototype = myToolbox.prototype = [];

myToolbox.prototype.show = function() {
    this[0].style.display = "block";
};

myToolbox.prototype.hide = function() {
    this[0].style.display = "none";
};




'Programming' 카테고리의 다른 글

C++ 0x : 람다(Lambda)  (0) 2013.04.14
(Visual C++ 2010) Examples of Lambda Expressions  (0) 2013.04.14
(JavaScript) Canvas tutorial - HTML | MDN  (0) 2013.04.03
(Java) Everything about Java 8  (0) 2013.03.28
(JavaScript) append text to body  (0) 2013.03.25