开发者

jQuery: extending, adding a new function and building a plug-in?

Today, my only pressing question about jQuery is about the when to use jQuery.extend() and, jQuery.fn (which is used for plug-in开发者_C百科s). Basil Goldman seems to have an explanation in “Defining your own functions in jQuery” but for some reason I’m still not satisfied that I have the best information. Once we start to work with jQuery.fn we must consider whether we should just build a full-blown plug-in. This implies three issues: extending, adding a new function and building a plug-in. There should be an explanation that coheres all three. Is this worthy of an explanation and do we have one?


I think you might be thinking too hard. :)

In the jQuery source - extend() is defined once and used in both namespaces:

jQuery.extend = jQuery.fn.extend =  function() { .. };

Technically, all this function does is merge together object properties.

So in the most basic use case, you just merge two objects into a single object (much like options parameters in plugins):

this.options = $.extend({}, defaultOptions, userOptions); // Just mergin' objects

The extend function on the plain-jane $||jQuery namespace merely adds that function as a static-like function in the jquery namespace. Functions that go on the jQuery namespace are generally ones that don't require an element to operate on. These are functions like isArray() and isFunction() along with a bunch more.

var noWhiteSpace = $.trim(string); // No element needed

jQuery.fn is more or less reserved for functions that perform actions based on the elements that are passed into the jquery object. These are like normal plugins, and most of the things you're used to in jQuery.

$('div').css('border', '1px solid green'); // Do work on a set of elements

More interestingly, if you look at something like the $.data() function in the jQuery source. It is defined in both namespaces. It is first defined in the $ namespace and takes and element as the first parameter. It is later extended onto $.fn and simply calls the first function with the first parameter set as 'this.'

Hope that's what you're looking for!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜