JavaScript库世界杯

爱它们或讨厌它们,JavaScript库在DOM脚本领域产生了巨大的影响。 随着AJAX的成熟,以及支持其扩展用途所需的脚本的复杂性增加,为每个项目从头开始生成自定义代码变得越来越不可行。

此外,AJAX的增长以及对Web 2.0应用程序的浓厚兴趣正吸引着许多新手。 毫不奇怪,他们不想花费漫长而艰辛的时间来吸收与浏览器错误和API差异搏斗所需的神秘知识。

无论您是老派的DHTML专家,还是想成为Web 2.0的专家,都该了解一些库了。 那么,那里有什么? 我很高兴你问!

在过去的一年左右的时间里,随着DOM脚本在AJAX背后的主流编码领域中爆炸式增长,看似无数的JavaScript库也加入了竞争者的行列。 幸运的是,对于我们的头脑不好的人来说,在采用程度,文档编制和社区支持方面,有四个图书馆已成为显而易见的先驱者:

  • Dojo,一个功能强大的库,主要是在JotSpot的背后开发的
  • 原型,Ruby on Rails的骨干,具有出色的AJAX支持
  • Mochikit,使JavaScript不那么吸引人的Python库
  • Yahoo UI库(通常简称为YUI),即将诞生

在这四个国家中,尚无明确的领先者。 每个库都在功能上与其他库上有很大的不同,但在易用性,社区支持和理念等不太明显的方面。 选择开发平台的最重要因素之一是其理念与大脑工作方式的契合度。

在本文中,我将研究每个库,以帮助您确定哪个库最适合您的开发风格和项目需求。 虽然不可能涵盖每个库的每个方面,但我已尽力介绍了每个库的重点,并提供了一些有关它们如何处理DOM操作,事件的基本任务的见解。处理和AJAX。

1537_dojo

道场

Dojo由主要开发人员Alex Russell(最近宣布他将全职从事Dojo)以及大约30名核心贡献者组成的团队维护。 该库主要由Jot资助,Jot是功能强大的Wiki引擎JotSpot的创建者。

Dojo可以从Dojo网站上以多种版本下载。 每个版本都将Dojo库的某些部分捆绑到一个JavaScript文件中,并允许您使用Dojo的导入机制动态加载该库的其他部分。 Dojo最受欢迎的版本是AJAX版本,压缩后的重量约为132K,并包括对异步I / O操作(用于AJAX调用),视觉效果,事件处理和Dojo基本库的支持。

在Dojo版本的顶部加载其他功能很容易。 例如,如果要添加加密库,则应编写以下代码:

dojo.require("dojo.crypto.*");

但是,出于性能方面的考虑,最好根据项目的需求选择合适的版本,并避免以这种方式需要额外的库。

就功能而言,Dojo无疑是这四个库中使用范围最广的,并且更加关注解决性能问题和浏览器兼容性问题。 还已经考虑了诸如SVG之类的技术来编写它,并且正在采取行动以交叉兼容的方式将Dojo的功能引入SVG。

从尽快处理字符串到有效的迭代,再到对AJAX中的后退按钮的内置支持,Dojo确实涵盖了所有内容。 但是,这意味着它具有相当大的API,并且鉴于目前的文档稀疏,因此与Dojo相关的学习曲线非常可观。

最近,Django框架开始在其管理系统中使用它的发行版捆绑Dojo,因此这可能是增加Dojo文档的催化剂。

基础

Dojo的核心是一种灵活,强大且易于使用的方法dojo.io.bind 。 可以以多种方式使用此单一方法来进行同步和异步调用。 为了让您了解它的灵活性,让我们看一些示例:

// Load a text document from the server, then alert the user of the contents. 
dojo.io.bind(
 {
   url: "http://example.com/document.txt",
   load: function(type, data, evt) { alert(data) },
   mimetype: "text/plain"
 }
);

// Serialize a form and send it to the server, then evaluate the response as JavaScript!
dojo.io.bind(
 {
   url: "http://example.com/comment.cgi",
   load: function(type, json) { alert(json.myProp) },
   formNode: document.getElementById("formToSubmit"),
   mimetype: "text/javascript"
 }
);
dojo.io.bind
dojo.io.bind( 
 {
   url: " http://example.com/comment.cgi",
   load: function(type, data) { alert(data) },
   backButton: function() { /* do something when back is pressed */}
 }
);

Read more about the full capabilities of dojo.io.bind in this introductory article .

The dojo.event method takes the approach of implementing its own event handling system, rather than providing a wrapper around the browser's event system. This results in quite a solid system and, like dojo.io.bind , it's both simple to use and exposes large amounts of power and flexibility.

You can read more about Dojo events here . In the meantime, let's take a sneak peek at the dojo.event method in action. As expected, the following code is triggered by the onClick event and uses an intuitive and familiar syntax.

dojo.event.connect(node, "onclick", "handleOnClick");

Highs and Lows

The great thing about Dojo is that it's so rich in features. The Widget system provides a raft of useful controls such as a DatePicker, a RichText widget, as well as a considerable number of controls that you would expect to find in something like Microsoft's MFC. In addition to this, you can build your own widgets on the framework using HTML, CSS and JavaScript ( see this article for details ).

But JavaScript need not be limited just to the browser, and Dojo is designed with this in mind. Dojo's platform independence could make it an interesting platform for desktop widget development, as well as many other potential applications. As an example, Open Laszlo recently announced that it was licensing Dojo for its JavaScript implementation of the platform.

Dojo's design has quite a Java-like aesthetic without trying to be Java. In fact, I'd say Dojo utilises JavaScript as a language exceptionally well. One downside of the library's design, though, is the sometimes long package strings that you need to type out to call the methods or instantiate the library's objects -- it would be nice if Dojo could provide a way to "mix" a package into the global or local scope. This would provide ready access to a certain package if you planned on using a lot of methods from it, although I'm not sure how easily it could be incorporated.

Additionally, for all its features, Dojo is completely missing any functions that could aid the selection of DOM elements -- something that's quite fundamental to DOM Scripting. It seems to be quite a gaping hole in the library -- it would be great to be able to select elements using CSS and/or XPath. Similarly, while some of the objects in the library seem to support a kind of iteration framework, Dojo is lacking in methods for iterating though arrays and collections, a task which seems to make up the bulk of DOM scripting tasks.
And at this point in time, documentation for Dojo is not at a premium. The official Dojo site contains some API documentation that's far from complete, but it does have some well-written articles highlighting areas of the library. The JavaScript community has yet to embrace the daunting task of documenting Dojo, though, so independent on the topic articles are few and far between.

1537_protoscript

Prototype and Scriptaculous

The development of the Prototype library is lead by Sam Stephenson of 37 Signals and, along with scriptaculous, has risen to fame as the JavaScript backbone of Ruby on Rails AJAX helpers.

Prototype itself contains the base-level functionality such as AJAX, DOM manipulation, event handling and some extensions to JavaScript itself, while the separate but very much related library, scriptaculous, developed by Thomas Fuchs, is based on Prototype and implements a whole raft of visual effects, as well as drag and drop and some user interface components.

Prototype can be downloaded from the Prototype site , or you can pull it straight from the Ruby on Rails subversion repository if you want to live on the bleeding edge. It currently weighs in at a reasonably compact 54KB. scriptaculous is available from the scriptaculous site and is split into three files: controls.js , dragdrop.js and effects.js , which weigh in at 28KB, 23KB and 32KB respectively. Ruby on Rails bundles all of these files by default.

For an overview of Prototype, take a look at my earlier SitePoint article, Painless JavaScript with Prototype .

The Basics

As far as DOM manipulation goes, Prototype sits very much on the innerHTML side of the innerHTML /DOM methods argument ,which may be a plus or a minus depending on which side of the fence you sit in that particular holy war.

Regardless, for most of the DOM lifting you'll need to do, Prototype is extremely useful. A new but very nice feature is that many methods are added directly into the nodes themselves. Here are a few examples:

$('form').visualEffect('fade', { duration : 3 }); 
$('loader').show();

This code fades out the form to which it is applied over a period of three seconds. You can even extend the node objects with your own methods. There have been some performance issues flagged with this approach, but I believe they have mostly been addressed.

Unfortunately, although Prototype has a set of methods for event handling, at this time they're pretty under-developed. Event.observe is more or less a wrapper around the well-used but now superceded addEvent by Scott Andrew-LePara. However, it's easy to use and capable of handling most circumstances. One nice aspect is that it automatically removes all the event handlers you set using Event.observe when the page is unloaded, which should help prevent IE from leaking memory.

The AJAX support is reasonably straightforward and very well developed, as it has been developed right alongside Ruby on Rails. It offers a host of excellent features that I find extremely useful.

It handles JSON transparently, and even evaluates JavaScript sent back from the server automatically. This is the basis of the much-lauded RJS technology in Rails, and is extremely powerful. You don't need Rails to take advantage of this, though -- you can make an AJAX request:

new Ajax.Request('new_comment.php',  
 {  
   data: 'comment=My comment.',  
   evalScripts: true  
 }
);

Then, you can return updates to the page from your server as JavaScript:

  $('comments').replace('<div class="comment">My   comment.</div>'); 

As you can see, this is an incredibly powerful way of designing AJAX applications.

Another nice little feature of the Ajax.Request object is that it appends the X-Requested-With HTTP header automatically, which enables you to tell if your requests come from AJAX on the server side.

Highs and Lows

Convenience is king with Prototype. Most notably, the $ function (which selects elements by id ) and the $$ function (which selects elements using CSS selectors) provide extremely quick access to elements on the page. The $$ function even supports CSS3 selectors -- most browsers don't. When you use it in conjunction with the enumerable methods and Prototype's other convenience methods, you can come up with some pretty concise statements. For instance, to hide all div elements with a class of /#c#"obscene":

$$("div.obscene").map(Element.hide); 
$$("a[href='http://']").each(function(element)  
 {
   Event.observe(element, 'click', openNewWindow);
 }
);

As we all spend most of our scripting time working through lists of DOM nodes, this buys us a lot of power indeed. The compact and intuitive API really is the killer feature of Prototype for me.

Scriptaculous is a great, extensive effects library with solid drag-and-drop support that, again, is ridiculously easy to use. Consider this:

new Draggable('my_element');

This produces an element that the user can drag. You can then add further configuration using object notation, like this:

new Draggable('my_element',  
 {  
   revert : true  
 }
);

Documentation was very limited for a long time, but recently many people have filled the gap, making Prototype one of the most widely documented of the big JavaScript libraries, albeit that that documentation is a bit splintered. There are no central API docs, but there's a whole raft of libraries that cover parts of the library, as well as Jonathan Snook's excellent cheat sheet detailing the entire library . The prototypedoc.com site also maintains a pretty thorough list of articles about Prototype to help you get started with the library.

1537_mochikit

Mochikit

Mochikit is the brain child of Bob Ippolito (the primary contributor) and is available from the Mochikit site . The basic package weighs in at around 90KB (compressed), but you can load each of the modules separately. Mochikit is also currently bundled with the Python web framework, TurboGears .

In the words of Bob,

We took all the good ideas we could find from our Python, Objective-C, etc. experience and adapted it to the crazy world of JavaScript.


So, to a large extent, Mochikit draws on the idioms of Python for its API. If you're familiar with Python, you'll have an instant head start with Mochikit, although it has a simple API which is reasonably easy to pick up. Of all the libraries covered in this article, Mochikit's API feels the most "designed". Rather than relying on package-style naming conventions, it exports a select number of functions to the global namespace, which helps make your scripts a lot more compact.

When getting started with Mochikit, you should:

  1. Watch Bob's screencast .
  2. Start bashing away using Mochikit's excellent interactive interpreter , much like you would with Python. This is a great way to get a feel for the library and a basic understanding of how Mochikit works.

The Basics

When working with the DOM, Mochikit has some real tricks up its sleeve:

var warning = P(  
 { 'class' : 'warning' },  
 "Please provide a ", STRONG(null, "valid email address")  
);  
swapDOM(document.getElementById("notifications"), warning);

This code will use the relevant W3C DOM methods to create the equivalent node tree for the following HTML:

<p class="warning">Please provide a <strong>valid email address</strong></p>

The Mochikit code is almost cleaner than the HTML syntax!

The Mochikit.DOM module also contains a number of other methods for easy DOM manipulation, such as the swapDOM method mentioned above (which does what it says on the tin), and toHTML (which converts a DOM node to the HTML it represents). And just for good measure, Mochikit has thrown in the $ function for those who are used to it.

As far as event handling goes, Mochikit has a well designed (if slightly unfamiliar system) that's implemented in the Mochikit.Signal module. It's based around the concept of connecting a listener to a signal that's sent from an object. All the regular DOM events are signals, but you can create your own, too. The connect method does all the work here:

// connects the onclick signal of the element with id="thing"   
// to the function showDialog, which points to the element.  
connect($('thing'), 'onclick', showDialog);  
 
// connects the onsubmit signal of element id="form" to  
// formController.checkSubmit, which points to the  
// formController object.  
connect($('form'), 'onsubmit', formController, 'checkSubmit');

You can make your own objects send signals simply with the signal method:

signal(anObject, 'a_signal');

While Mochikit's event system is a departure from the way you might normally expect event handling to work, it's actually brutally simple and great to use once you get used to it.

AJAX stuff is handled by the Mochit.Async module, and the Deferred objects which lie at the core of the implementation. To perform a basic AJAX call, use either loadJSONDoc or doSimpleXMLHttpRequest :

var request = doSimpleXMLHttpRequest('get_options.php',   
   { q : 'web developer'}  
);

This function returns a Deferred object, on which you can set callbacks:

request.addCallbacks(mySuccessFunction, myErrorFunction);

When the XMLHttpRequest is complete, the relevant callback is called and passed the XMLHttpRequest object as the argument:

function mySuccessFunction(req) {  
 alert(req.responseText);  
}

Deferred objects are useful for any asynchronous programming and are a great idea. Read more here , or watch the screencast for more details.

Highs and Lows

First off, Mochikit's logging framework is excellent. Simply add logging statements:

log("This is so much better than alert");  
log("ERROR This thing is broke");

You can then use Mochikit's bookmarklet to open a log window and view your log messages. You don't need to add anything into your pages or include any extra script -- it's truly effortless and beats alert any day.

Mochikit also makes full use of JavaScript's functional programming features to really enhance and simplify the library's API. For instance, if you want to sort a group of objects by their name properties, you can use keyComparator to create the sort function for you:

var sortedByName = people.sort(keyComparator("name"));

There's also the useful counter function. This creates a function which returns a value that's incremented by one every time it's called:

var nextId = counter();  
nextId(); //=> 1  
nextId(); //=> 2  
nextId(); //=> 3

There's also a full set of Python-style iteration functions, such as forEach , map and filter , which are sure to see heavy use.

As far as documentation goes, Mochikit has some very good API documentation, but details on some very basic parts of the library are a little lacking. In particular, after reading all the docs, watching the screencast and writing a few Mochikit-based scripts, I'm still unsure which version of the library is best suited for any purpose. Do I use the packed version or the main Mochikit.js ? How can I load individual parts of the library?
However, Mochikit does have a mailing list, so answers to these kinds of questions are, no doubt, not far away. All in all, Mochikit may not be what you're used to in terms of a JavaScript library, but it's beautifully designed and I'm looking forward to seeing where Bob takes it.

1537_yui

Yahoo! UI Library

The Yahoo! UI Library or (YUI as it's commonly been referred to) was developed by Yahoo! for internal use, but has recently been open sourced along with a whole raft of excellent developer resources at developer.yahoo.com .

YUI is more a distinct set of "utilities" than a coherent library, with five core scripts that cover:

  • 动画
  • AJAX
  • DOM操作
  • 拖放
  • 事件处理

共有六个控件,分别是:

  • 日历
  • 滑杆
  • 菜单
  • 自动完成
  • 树视图
  • 容器类(可用于实现所有形式的窗口样式小部件的容器)

您可以从developer.yahoo.com网站单独下载每个脚本。

这种松散耦合的设计库方法绝对有优势-例如,当用户只想使用事件系统时,让用户下载100 kb左右的库通常显得有些大材小用。

每个Yahoo! 库仅取决于小的yahoo.js文件。 另一方面,这种方法为开发人员提供了一些不太连贯的体验,并可能在库中引入一定的重复次数。

关于YUI感到尴尬的一件事是它的命名空间非常丰富。 您对库的每次调用都必须以庞大的包字符串作为前缀:

var myAnim = new YAHOO.util.Anim(  
 'test',  
 { height: {to: 10} },  
 1,  
 YAHOO.util.Easing.easeOut  
);  
myAnim.animate();

这一切似乎都很冗长,而且我不确定JavaScript是否确实需要这种程度的命名空间-通常我们永远不会在任何页面上加载这么多的代码。 尽管如此,YUI是一个简单而实用的库,其主要重点似乎是尽可能简单地解决浏览器差异。

基础

对于习惯于本机浏览器事件处理方法的用户,YUI的事件处理库应该具有非常熟悉的API。 但是,它为Yahoo!带来了一些惊喜。 开发人员Dustin Diaz已在其网站上进行了详细解释。 您可以这样设置一个简单的侦听器:

YAHOO.util.event.addListener('object_id', 'click', callBackFunction);

事件库的一个非常强大的功能是其事件监听器的延迟附件。 本质上,如果由于页面尚未加载而尝试将侦听器附加到尚不存在的元素上,它将透明地等待该页面变得可用,然后再附加到事件。 这是一个使许多DHTML新手感到困惑和沮丧的问题的巧妙解决方案。
DOM库通过浏览器不一致来抽象,从而允许样式的无缝设置和元素属性的报告。 但是,尽管它可以很好地处理常见任务,但是这里有一些惊喜:

  • get是臭名昭著的$函数的YUI版本。
  • 一种有趣的方法是generateId,它可用于以编程方式为元素生成ID,因此您可以在脚本中的其他位置快速访问它们。 但是,现在还不很清楚为什么将这种方法用于简单地存储对对象的引用,因此,我很想看到它在实际脚本中使用。

连接管理器包含所有YUI的AJAX魔术,并且与其他库一致,选择不采用高级方法。 它只不过提供了XMLHttpRequest的跨浏览器界面:

YAHOO.util.Connect.asyncRequest(  
 'GET',  
 'http://www.yahoo.com',  
 callback  
);

其中一个亮点是丰富的callback接口,它允许您定义一个包装了callback函数以及一些额外配置的对象。 这是一个示例callback对象:

var callback = {  
 success: function(resp) { alert('WOO!!'); }, // called on success  
 failure: function(resp) { alert('BOO!'); }, // called on error  
 argument: arguments, // user defined arguments  
 scope: formController // scope the callbacks are called within  
}

高点和低点

Yahoo!提供的文档 因为图书馆很棒。 该站点具有正式的API文档,大量示例,邮件列表以及对该库各部分主要功能的一些简短但清晰的解释。 但是,与Dojo和Mochikit一样,该库还没有像Prototype那样充分地吸引开发人员社区的想象力,因此,目前独立的文章还很少。 查看有关YUI的文章的最佳地点是Yahoo!。 开发人员, Dustin Diaz的网站

就像我在上面暗示的那样,事件处理实现是YUI的主要优势之一,并且它与库的其他部分脱钩的事实意味着它很可能独立于库的其余部分而看到大量使用。 但是,该库的其余部分虽然功能非常强大,但没有Mochikit,Dojo和Prototype之类的创新功能,并且由于包字符串长,因此使用YUI编码有时会花费很多时间。

但是,越来越多的组件列表非常丰富。 例如,“日历”组件支持多种语言和多种日期选择,“容器”类使您能够实现所有类型的窗口界面。 使用这些组件的一个缺点是,它们往往在很大程度上依赖于其他库。 在讨论这个问题时,Dean Edwards以树视图控件为例进行了重点介绍,该树视图控件使用了大约260K的JavaScript。

哪一个获胜?

好吧,对这个问题的简短回答是,没有一种真正的脱颖而出的解决方案在所有情况下都能胜任。

原型是最全面的文档-尽管形式不完整。 它似乎也是目前使用最广泛的库,可能是因为它确实在开发人员最常完成的任务(例如选择节点和处理列表)方面表现出色。 当然,这将成为Ruby开发人员的自然选择,因为它遵循许多Ruby习惯用法。 关于Prototype的另一件事是,它具有强大的Rails权重,因此,许多开发人员为Prototype提供了错误修复和补丁。 最后,它提供了丰富的附加库,例如scriptaculous,Rico和Behavior,这使其成为许多开发人员的理想选择。

另一方面,Prototype具有非常欠发达的事件处理框架,这对于功能强大的库来说是一个主要问题。 而且-纯粹是出于口味问题-Prototype对事物的超实用方法(例如大量使用innerHTML属性)有时看起来有些“肮脏”。

对于较小的项目,YUI的解耦设计和功能齐全的组件很可能是一个很大的优势。 轻松进入连接管理器或事件库并执行一些基本任务,而无需遍历过多的学习曲线,这非常容易。 总体而言,就酷炫或强大的功能而言,它没有太多提供。

Dojo绝对是其中的佼佼者-您几乎总是可以依靠它来实现任何功能的最强大实现。 如果您正在计划一个JavaScript密集型应用程序,Dojo对性能的关注绝对是天赐之物。 小部件实现还具有构建复杂UI的巨大潜力。 但是,无论从文件大小还是API大小来看,它确实相当大,因此我不建议在较小的项目中使用它。

在我看来,Mochikit是迄今为止四种设计中最精心设计和最周到的,Python / Twisted / Nevow开发人员一定会发现其API非常熟悉。 但是,它的文档在某些地方有些薄(例如,我不确定要在脚本标记中放入哪个版本的Mochikit发行版)。 此外,它使用的某些惯用法和功能技术可能会使初学者或对功能编程技术不太熟悉的人感到困惑。 但是,确实值得一看。 Mochikits的功能可能会让您感到惊讶createDOM函数,迭代工具和异步体系结构是一件艺术品。

From: https://www.sitepoint.com/javascript-library/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值