Encapsulation for distribution
The last aspect of developing modern professional JavaScript code is encapsulation processing for code distribution or use in the real world. As developers start using more and more JavaScript code in their pages, the possibility of conflict will increase. If both JavaScript libraries have a variable called data or add events according to their intentions, catastrophic conflicts and inexplicable errors may occur.
The ability of developers to simply place <script> pointers to work properly without any changes is the essence of developing a successful JavaScript library. There are many types of technologies or solutions that developers use to keep their code clean and generally compatible.
Using namespaces is a widely used technique that ensures that code does not affect and conflict with other JavaScript code. An extreme (but not necessarily the best or most useful) example of this is the user interface library that anyone developed by Yahoo can use. An example of using this library is shown in Programs 1-3.
Program 1-3. Add events to an element using the heavily namespaced YahooUI library
//Add mouseover event listener to element with ID "body"
('body','mouseover',function(){
//and change the background color of the element to red
= 'red';
});
However, this namespace approach has a problem with the lack of inherent consistency between libraries in terms of how they are constructed and used. It is at this point that central code repositories such as JSAN (JavaScript Archive Network) become very useful. JSAN provides a set of consistent rules that code libraries need to follow, and a way to quickly import other libraries on which code depends. Figure 1-2 shows a screenshot of the main distribution center of JSAN.
Figure 1-2. Screenshot of the public code repository JSAN
In Chapter 3, I will explain the details of developing clean encapsible code. In addition, other common accidents such as incident handling conflicts will be discussed in Chapter 6.