Create jQuery Library with Vanilla JS
July 28, 2015
It's kind of fun project. Create jQuery Library like functions with vanilla JS.
$ object
What is $? $ is not a special keyword. It is just a variable name. It will return every incidet of argument from DOM. The task is to create an array like element (must have a function of length) when it is called $(); so we can manuplate the DOM.
Most important concept here is that 'this'. The reason we are creating $ is that we want to return every elements that are instance of $. Without it, we can't call $('selector').OTHERFUNCTION.
$.expend(target, object)
Don't think too hard. You will ruin it. This was one of the function that I was most struggle with. How to make sure that the function is assigned as same as other function? Just assign it.
$.isArray(obj)
This will return true if the object is Array (not Arraylike obj)
This is something to remember. To see if the argument is true array, the only way to check is to see toString.call(obj) and return '[object Array]'
$.ArrayLike(obj)
Like what $(); returns, arraylike stuff but not exactly an array. So what's difference between array and array-like obj? An array-like object has:
$.each
As you guess, each function is one of the fundamentals. One thing about this challenge is that the cb looks like function(index, value) {};
$.makeArray
This function returns new array. To do so we can use $.each()
$.proxy
Take a function and retuns a new one that calls the original with a particular context.
The key here is to invoke the function with apply, we need another function. The proxy returns a function which will call the function. The reson is that if the function being called then it will set 'this' something other than context.
$.html(mewHTML)
There is a property called 'innerText' which returns text within the element
$.text(newText)
The text function will get/set the text portion of an element. This is actually big hard question. Let's take a look more on textnode.
textnode is literally 'text' in the element. It is possible to create text node like var text = document.createTextNode('hello');. More importantly, each node like elementnode and textnode has different value.
The challenge of this problem is if argument is not passed, first, we have to get all textnode from each and every nested elements. If the element's child nodetype === 3, which is TEXT_NODE, then it will return, otherwise go down to child's child node until it finds text node to return