3个流行的JavaScript库一起学

JavaScript frameworks are a boon when you have lots of ideas to turn into functional, clean code. And with the meteoric rise of web applications using AJAX technology, frameworks like jQuery are necessary to reduce the time you spend implementing the required functionality. And looking around you see jQuery this and jQuery that with little to no mention of other frameworks. Fact is, there are a ton of other frameworks which are just as elegant as jQuery. Today we are going to take a look at two frameworks which promise to make writing code easier. Do note that I use the words library, framework and toolkit interchangeably. I am not going to go into semantics and neither should you. Each of these libraries try to accomplish different things. We are only going to look at the parts where their intended functionalities overlap.

JavaScript frameworks

Basic Functionality(基本功能)

我们在JavaScript的学习中,大多数人的JavaScript代码可以被分解成许多小块,大概可以分为以下类别:

DOM ready(DOM加载)

A JavaScript developer runs into this problem sooner or later: his pristine code just won’t run. He has debugged the code again and again but to no avail. The problem is that the code is just placed at the top of the page. When the script is executed, the elements he is referring to in his code don’t even exist in the DOM leading to these errors.

Remember, script calls are synchronous. This means that when a browser sees a script tag, it ceases loading everything else until the scripts are loading. This is in stark contrast to its general loading mechanism where other objects are often loaded asynchronously.

You could always work around this by just placing the code at the bottom of the page but you never know. With this in mind, most libraries provide a DOM ready function to make sure the code is only executed after the DOM is ready to lock n’ load but before the images are completely loaded.

With raw JavaScript, you’d be looking at something like this.

1
window.onload = someFunction; 

 

Accessing elements(访问元素)

You obviously want to access specific elements and manipulate them somehow. Unfortunately, IE is rather finicky and can break your code. To let developers write better code, each library provides a cross browser method which lets you access a specific element. Most libraries use CSS style selectors to zero in on their target elements to make the learning curve shorter and much more importantly, cleaner looking code.

Without a framework, you’d have to do this:

1
2
var elem = document.getElementById('header');  
var io = document.getElementsByTagName('input');

Manipulating elements(操作元素)

Of course, once you’ve obtained the element, you’d want to perform some operation. This includes adding or removing a class, toggling its visibility, changing its dimensions, editing its contents and so on. As always writing all this in raw JavaScript can be painful. Each of these libraries provide wrapper functions to do all of the above noted work and lots more.

With raw JavaScript, your code would look like so:

1
 document.getElementById("title").innerHTML="Title";

Manipulating the DOM(DOM操作)

Often, you’d want to directly change the nodes in the DOM. You might want to create a new wrapper object to which you want to put your recent Twitter status in or you might want to remove a div element for an email app you are writing. In each of these cases, you’d want to manipulate the DOM efficiently and all of these libraries provide methods to do so in a clean manner.

Appending an element would take this much code with raw JS.

1
2
 var myElement = document.createElement("<div>Sometext</div>");  
 document.all.myBody.appendChild(myElement);

Hooking up events (事件连结)

Events are the building blocks of any application and one of the more peskier parts of cross browser scripting. The thing is, W3C defines one way and IE does its own thing. To over come this, all of these libraries provide ways to attach or unattach even handlers to specific events of the element.

Hooking up events in raw JavaScript.

1
element.addEventListener('click',doSomething,false)

AJAX request(AJAX请求)

Native JavaScript using the XHR object is tedious to write and debug. In order to let developers write code more easily each of these frameworks abstracts the tedious details of implementing an AJAX request behind a simple function call with methods to call when the request succeeds or fails.

I am not even going to try and post some code to make AJAX request with raw JS. Instead you should look at Jeffrey’s excellent screencast. Shortly, we’ll see how a framework drastically cuts down your code.

jQuery

Ah, all pervading jQuery. It has been the talk of the town among web developers for a while know and rightly so. jQuery doesn’t try to do too many things. You aren’t going to find a dozen plus widgets bundled with the base build or ways to support classes or class based objects. jQuery focuses primarily on the DOM and I think they’ve done an excellent job.

If your work is primarily DOM related, jQuery is the way to go. The syntax is among the easiest and a lot of times it feels like reading pseudocode than actual, working code. The community is big and friendly and there are a ton of plugins you could just drop in for added functionality. Plus there is the UI library if you want to add some common widgets to your site.

jQuery’s user base includes:

  • Google
  • IBM
  • Microsoft
  • Amazon
  • Dell
  • Twitter
  • ESPN
  • Digg
  • Netflix
  • Mozilla
  • WordPress

Extremely impressive if you ask me.

Now, we’ll look at how jQuery lets us reduce the time we spend coding before we look at the other frameworks.

DOM ready(DOM加载)

1
2
3
$(document).ready(function () {
    // Your stuff here
});

Accessing elements(访问元素)

1
2
3
var container = $("#main");
var posts = $(".post");
var headings = $("h1");
1
2
3
$("span:has(a)").doSomething();  
$("ul li:nth-child(3)").doSomething();  
$("p:hidden").doSomething();

Manipulating elements(操作元素)

1
2
3
$("div").attr("class", "clicked");
$("div").html("<span>Hello</span>");
$("span").addClass("current");

Manipulating the DOM(DOM操作)

1
2
3
$("#post").after("<div>Comments</div>");
$("p").wrap("<div></div>");
$(".comment").append("<span>Posted by</span>");

Hooking up events (事件连结)

1
2
3
4
5
6
// Using anonymous functions
$("#submit").bind("click", function(e){
// Your code here
});
// Passing in a functions name    
$("#submit").bind("click", evHandler);

AJAX request(AJAX请求)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$.ajax({
  type: "GET",
  url: "test.html",
  success: function(xhr){
    //Some code here
  },
  error: function(xhr){
    //Some code here
  }
 
  $.ajax({
  type: "POST",
  url: "test.php",
  success: function(xhr){
    //Some code here
  },
  error: function(xhr){
    //Some code here
  }
 
});

Equivalent code

1
2
3
$("#maintrigger").click(function () { 
      $("p").after("<div>Clicked</div>");
});

Prototype

Prototype is the grand daddy of JavaScript frameworks. It provides all the niceties you’d expect off a mature framework and then adds a little more. It also provides a number of library functions to help you write nicely abstracted, object oriented code.

Prototype’s user base includes:

  • Apple
  • NASA
  • 37 Signals
  • hulu
  • Rails
  • Backpack
  • Gucci
  • last.fm
  • Wired
  • Prada
  • Dreamhost

A lot of well known, top tier names there. As I said, Prototype used to be the framework of choice for a long time before jQuery came in.

Now that the introductions are done, let’s see how Prototype can help you write better JavaScript.

DOM ready(DOM加载)

1
2
3
document.observe("dom:loaded", function() {
  // Your code here
});

Accessing elements(访问元素)

1
2
3
4
5
//Access an element with an id of post
$('post');
 
//Use the CSS selector engine
$$('.comment');

Manipulating elements(操纵元素)

1
2
3
$('post').addClassName('author');
$('container').getWidth();
$('post').hide();

Manipulating the DOM(DOM操作)

1
2
3
$('post').wrap('div', { 'id': 'container' });
$('post').update('<p>Some random text</p>');
$('post').insert('div', '<p>Some random text</p>');

Hooking up events (事件连结)

1
2
3
4
5
6
7
// Using anonymous functions
$(btn).observe('click', function(event){
//Your code here
});
 
// Passing in a function's name 
$(btn).observe('click', doSomething);

AJAX request(AJAX请求)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
new Ajax.Request("test.html", {
  method: 'get',
  onSuccess: function(transport) {
  // Some code here
  },
  onFailure: function(transport) {
  // Some code here
  }
});
 
new Ajax.Request("test.php", {
  method: 'post',
  onSuccess: function(transport) {
  // Some code here
  },
  onFailure: function(transport) {
  // Some code here
  }
});

Equivalent code

1
2
3
# $("maintrigger").observe('click', function(event){  
#   $("text").insert('<div>Clicked</div>');  
#  });

Mootools

Mootools doesn’t profess to be an easy framework to learn. Let’s face it, its web page says it is a web application framework for intermediate to advanced web developers. Don’t let them fool you. It is an extremely elegant framework which lets your create extremely classy JavaScript. It focuses on JavaScript as a whole instead of just the DOM. With that in mind, it provides a number of functions to speed up your workflow and also extends the DOM wherever possible. And just like Prototype, it contains a class creation and inheritance system which should make those coming from C# or Java more comfortable with JavaScript.

Companies which use MooTools include:

  • Ferrari
  • Vimeo
  • Palm
  • Nintendo
  • Formula 1
  • GameSpot
  • CNet
  • Joomla
  • phpMyAdmin
  • Jeep
  • Bing

Another framework with a very impressive user base.

Let’s now look at how MooTools makes your life as a JavaScript developer easier.

DOM ready(DOM加载)

1
2
3
window.addEvent('domready', function() {
    // Your code here
});

Accessing elements(访问元素)

1
2
3
4
5
6
7
// Use the $ function
$('someElement');
 
// Use CSS selectors
$$("#main");
$$(".post");
$$("h1");

Manipulating elements(操纵元素)

1
2
3
4
5
6
7
$('someElement).hasClass('clicked');
// Returns true if the element indeed has that class
 
$("someElement").setProperty('class', 'clicked');
 
$("someElement").empty();
// Empties the element of all its children

Manipulating the DOM(DOM操作)

1
2
3
4
5
6
7
8
9
var someElement = new Element('div', {id: 'mySecondElement'});
someElement.inject(someOtherElement);
// Injects the contents of someElement within someOtherElement
 
$("someElement").destroy();
// Removes element and all its children from the DOM
 
$('someElement').clone().
// Makes a copy of the element

Hooking up events (事件连结)

1
2
3
4
5
6
7
// Using anonymous functions
$('myElement').addEvent('click', function(){
    // Some code
});
 
// Passing in the functions name
$('myElement').addEvent('click', doSomething);

AJAX request(AJAX请求)

1
2
3
4
5
6
7
// A GET request
var myRequest = new Request({method: 'get', url: 'test.html'});
myRequest.send();
 
// A POST request
var myRequest = new Request({url: 'test.html'});
myRequest.send(someData);

Equivalent code

1
2
3
4
5
$$("#maintrigger").addEvent('click', function(){
   var elem = $("text");
   var someElement  = new Element('div');
   someElement.appendText("Clicked!").inject(elem, "after");
});

Code Comparison

jQuery

1
2
3
$("#maintrigger").click(function () {   
      $("p").after("<div>Clicked</div>");  
});

Prototype

1
2
3
$("maintrigger").observe('click', function(event){  
     $("text").insert('<div>Clicked</div>');  
});

MooTools

1
2
3
4
5
6
7
 
 
 $$("#maintrigger").addEvent('click', function(){  
    var elem = $("text");  
   var someElement  = new Element('div');  
   someElement.appendText("Clicked!").inject(elem, "after");  
});

本文《3个流行的JavaScript库一起学》是《Learn 3 Excellent JavaScript Libraries at Once》的精简版,想了解更多的有关内容请看原文。

原文来自:Learn 3 Excellent JavaScript Libraries at Once

 

站点统计