开发者

Why build Javascript functions as jQuery plugins?

I've seen alot of jQuery implementations of existent JavaScript functions that merely wrap the JavaScript code in a jQuery wrapper and don't actually rely on any of jQuery's base for their operation.

What are the benefits of using Javascr开发者_如何转开发ipt as a jQuery plugin?

If there are none is there a speed loss to use a jQuery plugin that could have easily been implemented outside the wrapper just as well?

Many thanks in advance (just trying to learn something here).

Updated with example:

http://plugins.jquery.com/project/base64

was originally

http://www.webtoolkit.info/javascript-base64.html


Much of jQuery is just a clever wrapper around existing JavaScript functions. $('#some-element') is perhaps a little easier to type than document.getElementById('some-element') but is otherwise not much different.

(I exaggerate, but only slightly.)

The main utility of jQuery is being able to combine together its various components. If I can select elements with a jQuery selector and then perform some action on those elements directly through a jQuery function, that's preferable to having to extract the underlying DOM elements and manipulate them manually, for example.

So it really depends on what functions you're seeing get wrapped. Some of them might very well add no value, and the authors are simply accustomed to everything being in jQuery. (We definitely see that phenomenon on StackOverflow — people who can't find a standard JavaScript function simply because it's not in the jQuery documentation). In other cases, there might be some hidden benefit even if the wrapper does little if anything to modify the underlying function's behavior.


There's also a lot of momentum around jQuery, and general trust. Including arbitrary javascript in your code base may not be as 'acceptable' to higher-up-types as including a new jQuery plugin.

So it may be a mistaken perception, but by being a jQuery plugin, a library benefits by being associated with high quality code.


IMHO the only reason to create a plugin is to execute some functionality against a selector ie a set of selected elements eg

$('.myelements').someFunction();

If your plugin ends up looking like this (case in point the newly released Microsoft Globalisation plugin)

$.doSomeStuff();

then there isnt much benefit that couldn't be gained from using a closure. However a lot of developers dont understand closures and namespaces in javascript, and by following a plugin development templatethey can get the benefit without fully understanding the pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜