Learn jQuery from jqLite
JQuery
Jquery is a great library, it makes manipulating DOM element and browser really simple and easy.
As a web developer, jQuery is our day to day tool. However, sometimes it just too convenience that
we forget how to make web page without it. It is important to go back to see how jQuery handle and wrap
the DOM api and provide the simple interface for us.
JQLite
Angular.js comes with a simple compatible implementation of jQuery, called JQLite.
JQLite is used internally for angular.element if user doesn’t include jQuery, as a
replacement for jQuery. It only have 1000 lines of code with lots comments,
So it’s a good starting point to understand how jQuery works.
initialize element
jQuery wrap the html DOM with jQuery object, as in JQLite:
1 | function JQLite(element) { |
After initialize, we get a new JQLite object with html DOM inside. then we can call
the jquery api to manipulate to inside element.
ready
One thing jquery provide is $.ready, which will execute the block inside only when
dom is ready
1 | JQLite.prototype.ready: function(fn) { |
From the source, we can know jquery check the document.readyState,
DOMContentLoaded event and window.onload event for the ready function.
attributes
jquery provides good api to set the attributes of DOM element, include css,
attr, prop. lets take css as example:
1 | // removed ie hacks... |
One reason that jquery interface is easy to use is, it provides single function
for both getter and setter. If we pass value, css function is a setter,
otherwise it returns css value of name.
Also, jquery object may include multiple elements, so inside the jquery object,
the css function is wrapped to execute on multiple elements:
1 | JQLite.prototpype[name] = function(arg1, arg2) { |
jQuery object provide both setter and getter on same function, multiple assignment,
short function name and also chaining. It is a really sophisticate api.
events
One thing jquery handled is event, in the time before jquery, people need to
handle different event api between IE and others. Lets see how JQLite handle this:
1 | // mapping addEventListener (not IE) and attachEvent (IE) events api. |
conclusion
After review the JQLite source, we can better understand the jQuery API
and how jquery works. And why you can do things such as combine getter and setter,
chaining and multi element assign. Learning those skills can also help us to design better API.
Comments