Design Patterns used in the jQuery library - javascript

jQuery is highly focused on the DOM and provides a nice abstraction around it. In doing so, it makes use of various well known design patterns which just hit me yesterday. One obvious example would be the Decorator pattern. The jQuery object provides new and additional functionality around a regular DOM object.
For example, the DOM has a native insertBefore method but there is no corresponding insertAfter method. There are various implementations available to fill this gap, and jQuery is one such library that provides this functionality:
$(selector).after(..)
$(selector).insertAfter(..)
There are many other examples of the Decorator pattern being heavily used in jQuery.
What other examples, big or small, of design patterns have you noticed that are part of the library itself? Also, please provide an example of the usage of the pattern.
Making this a community wiki as I believe that various things people love about jQuery can be traced back to well known design patterns, just that they are not commonly referred to by the pattern's name. There is no one answer to this question, but cataloging these patterns will provide a useful insight into the library itself.

Lazy Initialization:
$(document).ready(function(){
$('div.app').myPlugin();
});
Adapter or wrapper
$('div').css({
opacity: .1 // opacity in modern browsers, filter in IE.
});
Facade
// higher level interfaces (facades) for $.ajax();
$.getJSON();
$.get();
$.getScript();
$.post();
Observer
// jQuery utilizes it's own event system implementation on top of DOM events.
$('div').click(function(){})
$('div').trigger('click', function(){})
Iterator
$.each(function(){});
$('div').each(function(){});
Strategy
$('div').toggle(function(){}, function(){});
Proxy
$.proxy(function(){}, obj); // =oP
Builder
$('<div class="hello">world</div>');
Prototype
// this feels like cheating...
$.fn.plugin = function(){}
$('div').plugin();
Flyweight
// CONFIG is shared
$.fn.plugin = function(CONFIG){
CONFIG = $.extend({
content: 'Hello world!'
}, CONFIG);
this.html(CONFIG.content);
}

The Composite pattern is also very commonly used in jQuery. Having worked with other libraries, I can see how this pattern is not so obvious as it looks at first sight. The pattern basically says that,
a group of objects are to be treated in the same way as a single instance of an object.
For example, when dealing with a single DOM element or a group of DOM elements, both can be treated in a uniform manner.
$('#someDiv').addClass('green'); // a single DOM element
$('div').addClass('green'); // a collection of DOM elements

How about the Singleton/Module pattern, as discussed in this article about YUI: http://yuiblog.com/blog/2007/06/12/module-pattern/
I believe jQuery uses this pattern in its core, as well as encouraging plug-in developers to use the pattern. Using this pattern is a handy and efficient way of keeping the global namespace clear of clutter, which is further useful by assisting developers in writing clean, encapsulated code.

In the eyes of functional programming, jQuery is a Monad. A Monad is a structure that passes an object to an action, returns the modified object and passes it on to the next action. Like an assembly line.
The Wikipedia article covers the definition very well.

Related

Is there a risk involved in using MDN bind polyfill?

I have developed a Javascript library which requires the bind method.
Unfortunately, bind is not supported by IE8.
There are a polyfill on the MDN website which work well.
My question is:
Are there problems or possible incompatibility between this polyfill and other Javascript libraries ?
It is safe to use in any case?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
For me most obvious differences with native bind are:
arguments.caller does not point to the caller of bound function, but you shouldn't use it anyway
length of bound function is set to 0, this may affect function arity checks like https://github.com/fitzgen/wu.js/blob/master/lib/wu.js#L406
IMHO if you are using only "the good parts" of JavaScript, and not developing core of some framework (for IE8?), you shouldn't face any problems with this polyfill.
The answer is pretty much there on the MDN page itself:
"If you choose to use this partial implementation, you must not rely on those cases where behavior deviates from ECMA-262, 5th edition! With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when bind() is widely implemented according to the specification."
There's nothing wrong with the MDN shim as such. However if you choose to use their shim make sure that it can't be overridden by other libraries. I had an issue a while ago with Strophe doing just that and replacing one shim with another.
I tend to use underscore to cover stuff like this but there are other options like es5shim. With underscore you have a method called (you guessed it) '.bind' and works slightly differently to MDN's shim (uses 'new' invocation). Underscore also has a great method called '.partial' which can be useful in scenarios where you don't want to change the value of 'this' but partially apply arguments.
The point I am making here is that instead of shimming, maybe look at something that is properly protected/encapsulated within a library. The chances are you're going to need more than one shim in any case if you're targeting browsers like IE8.
Lastly, and not so importantly check out the performance tests at:
http://jsperf.com/browser-vs-es5-shim-vs-mdn-shim

When to use jQuery wrapper methods instead of built-in javascript methods

Which jQuery methods should be avoided in favour of built-in methods / properties?
Example:
$('#el').each(function(){
// this.id vs $(this).attr('id');
// this.checked vs $(this).is(':checked');
});;
I use the direct javascript property like this.id in these cases:
Whenever it does exactly what I want.
When speed is important.
When all browsers I care about support exactly what I need.
I use the jQuery access method when:
There are cross browser support issues or I'm not sure that there aren't cross browser issues.
When the jQuery way has more or enhanced functionality that is useful in my circumstance.
When it's part of a chained operation and chaining works better with jQuery.
When I'm already using jQuery for this operation and it seems inconsistent to mix/match some direct access and some jQuery access.
For example: str = $(elem).html() doesn't really have any advantages over str = elem.innerHTML, but $(elem).html(str) does have some advantages over elem.innerHTML = str; because the jQuery method will clean up the objects that are being removed more completely than the innerHTML way.
This is a broad question but here's a couple of guidelines that I think are useful.
You can/should use native js methods when:
You know what you are doing. That is you know the spec and any possible inconsistencies between browsers.
You are writing performance-critical piece of code where convenience is not top priority
You are not satisfied with the way library function works. This can break down to the following:
library implementation is buggy (that happens)
library implementation is incomplete (e.g. doesn't yet support some new features that are OK to use in your case)
simply your vision of some feature is different from library's implementation
The first condition should be true in any case :) The others can combine or go separately. I understand that they are all debatable and can provoke long talks on philosophy but I think they are good starting points and summarize lots of cases.
But the bottom line is - if you don't have a reason to avoid library methods, use them!
Most DOM properties are problem-free in all major browsers. For the two examples you mention (id and checked), the DOM properties are 100% reliable and should be used in preference to the jQuery equivalent for reliability, performance and readability.
The same goes for all properties corresponding to boolean attributes: readonly, disabled, selected are common ones. Here are some more. className is also 100% solid. For other properties and attributes, it's up to you. Using a library like jQuery may be the best approach for these if you're unsure and can afford to lose some performance (usually the case).
Stack Overflow regular Andy Earnshaw has blogged about this: http://whattheheadsaid.com/2010/10/utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element

How to take advantage of closure compiler when using a library?

I've recently been playing with the awesome tool from google that does some code-optimization and partial execution, for instance it would take something like:
//Just an alias for an elementByID selector
function $(bar){
return document.getElementById(bar);
}
//Call the selector
alert($("foo").value);
And shorten it into alert(document.getElementById("foo").value);, which is fairly awesome from an optimization viewpoint.
I'm only explaining this because I would have thought this concept works for larger libraries such as jQuery, which basically attempts to abstract away a bunch of things JavaScript does, like select by IDs.
In a quick test, I loaded the whole jQuery production file up to the compiler and appended a single bit of text at the end of it: alert($("#foo").val());
And quite tragically, the compiler wasn't able to map through jQuery's design and result with the simple example I had above, but rather my output is about 85kb of text with alert($("#foo").K()); stuck on the end. Basically, I just have minified code, and didn't take advantage of the awesome feature demonstrated above.
So my question is, if I do end up using a library, how can I code in such a way that closure compiler is able to simplify my code to it's native JS (or something more effective than 85kb of unused code)? Alternatively, what design should someone take if they wanted to make a small library that plays nice?
AFAIK, jQuery is not (yet) written to be optimized by the Closure Compiler's Advanced Mode. It has an "externs" file which will enable its public properties and classes not to be renamed, but it does not enable most of the optimizations (e.g. dead code removal) as you've discovered. Which is quite a pity, because the jQuery object, if property written, does lends itself quite readily and nicely to the Closure Compiler's prototype virtualization feature.
Slightly off-topic
If you are not tied to jQuery, you may consider the Dojo Toolkit, which can be modified to be used with the Closure Compiler while enabling most optimizations (especially dead-code removal).
See this document for details.
jQuery takes special pains to minify itself and in the process makes itself opaque to the Closure Compiler.
Closure Library is an example of a library that is written to make good use of the Closure Compiler.
Generally, the compiler does best with prototype inheritance and simple structures:
/** #constructor */
function Class () {}
Class.prototype.f = function() {};
With an explicitly exported interface:
window['MyLib'] = { 'method', method };
Generally, advanced mode only makes sense for a library if it has a small external interface relative to the amount of internal code. However, I definitely would encourage writing your library so that it can be consumed by an advanced mode compiled project (this requires separating out the export used when it is used as a stand-alone library, if they library itself is minified using advanced mode).

Prototype or jQuery for DOM manipulation (client-side dynamic content)

I need to know which of these two JavaScript frameworks is better for client-side dynamic content modification for known DOM elements (by id), in terms of performance, memory usage, etc.:
Prototype's $('id').update(content)
jQuery's jQuery('#id').html(content)
EDIT: My real concerns are clarified at the end of the question.
BTW, both libraries coexist with no conflict in my app, because I'm using RichFaces for JSF development, that's why I can use "jQuery" instead of "$".
I have at least 20 updatable areas in my page, and for each one I prepare content (tables, option lists, etc.), based on some user-defined client-side criteria filtering or some AJAX event, etc., like this:
var html = [];
int idx = 0;
...
html[idx++] = '<tr><td class="cell"><span class="link" title="View" onclick="myFunction(';
html[idx++] = param;
html[idx++] = ')"></span>';
html[idx++] = someText;
html[idx++] = '</td></tr>';
...
So here comes the question, which is better to use:
// Prototype's
$('myId').update(html.join(''));
// or jQuery's
jQuery('#myId').html(html.join(''));
Other needed functions are hide() and show(), which are present in both frameworks. Which is better? Also I'm needing to enable/disable form controls, and to read/set their values.
Note that I know my updatable area's id (I don't need CSS selectors at this point). And I must tell that I'm saving these queried objects in some data structure for later use, so they are requested just once when the page is rendered, like this:
MyData = {div1:jQuery('#id1'), div2:$('id2'), ...};
...
div1.update('content 1');
div2.html('content 2');
So, which is the best practice?
EDIT: Clarifying, I'm mostly concerned about:
Memory usage by these saved objects (it seems to me that jQuery objects add too much overhead), while OTOH my DOM elements are already modified by Prototype's extensions (loaded by default by Richfaces).
Performance (time) and memory leakage (garbage collection for replaced elements?) when updating the DOM. From the source code, I could see that Prototype replaces the innerHTML and does something with inline scripts. jQuery seems to free memory when calling "empty()" before replacing content.
Please correct me if needed...
You're better off going with jQuery. Both frameworks are great (and I use them both), but in your case jQuery is probably the winner.
In my opinion prototype provides a more natural syntax for javascript development. It does this at the cost of adding methods to some of the core classes, but it's also motivated by ruby where this is the norm.
jQuery on the other hand is far superior at dom manipulation and event observation. Your code will be more concise and manageable in these cases and will benefit from great performance features like event delegation. jQuery also has a much larger community and way more plugins and code samples.
If you're only interested in the three basic methods "update", "hide" and "show" then jQuery is better suited. It is aimed more at DOM manipulation which is exactly what you need. Then again you could do each of those things in a couple of lines of code, saving the 26KB needed to transfer the jQuery library.
Since your worry is in memory usage look at the jQuery file, it is 77KB uncompressed, how much work do you suppose that is for the browser to execute? Probably much more than that freed by calling empty() on a typical DIV.
And you mention Prototype is already in use on the site in which case you shouldn't be adding another library. jQuery's abilities are a subset of Prototype's.
This question is nearly a year old so you've probably made your decision by now. For anyone else reading the answer is simple; If something's not broken don't fix it, you already have one capable library installed so use that.
I would go for jQuery. Prototype used to modify default JS objects, which is fine but it means you have to be careful. I believe this is no longer the case though. JQuery also has a large plugin repository and the jquery UI extension for widgets. Btw. With JQuery you can use the familiar dollar sign as well.

OO JQuery and classes

I'm working on a site and using JQuery for essentially the first time. I've mostly used MooTools for previous projects, and I have a few widget classes I've written using the MooTools Class structure. I'd like to port them over to JQuery, but it looks to me like there is nothing similar to the MooTools functionality when it comes to object classes.
I've searched around a bit, and haven't found much on it. Digg appears to have rolled their own, but I'm not sure if this is something I should be using. Is there a better way? How object-oriented do people normally get with JQuery? What's the usual method of encapsulating a UI widget (or any functional class structure)?
I'll post a fake example of a possible MooTools widget class:
var ZombatWidget = new Class({
Extends: BaseWidget,
widgetPropertyX = 'prop1',
widgetPropertyY = 'prop2',
attach = function(el) {
var f = function() {
//do something widgety
};
el.addEvent('dblclick',f);
el.addClass('widgetized');
}
});
var z = new ZombatWidget();
z.attach($('widgetDiv'));
What I've got is a lot bigger than that, but you get the idea. Do I need to convert this to the prototype method of class/inheritance structuring? How would you write this kind of object class using JQuery?
You might find this approach useful to the task at stake: building an object-oriented jquery plugin.
And this article on Ajaxian "a real OO class system with jquery".
Hm... interesting. We have jQuery which imho is a great tool to interact with the DOM. It's a selection tool where you can write your own code (plugins) to modify selected items. You can interact here with your own (object oriented) code in a plugin to do something really cool.
So why would you need extra OO capabilities in jQuery unless you want to be able to inherit from other jQuery plugins?
Because you might have a plugin that allows you to do the following:
$(".spiffyness").yourSpiffyficationPlugin1();
And, while doing some really cool awesomeness already, you need more spiffyness on top of this.
Therefore you want to inherit from your first plugin which results in:
$(".spiffyness").yourSpiffyficationPlugin2(); //plugin inherited from 1
But... wouldn't you get there too by doing this:
$(".spiffyness").yourSpiffyficationPlugin1().yourSpiffyficationPlugin2();
Where the second plugin just does this tiny (but awesome ;)) thing extra on top of the first one?
In other words: is what you want, worth the effort for the sake of OO purism? Or is the jQuery pipe mechanism good enough and maybe everything you need?
I would say that separation of responsibilities and/or your mootools mindset might be the real issue here. Let jQuery do what it is good at, use it's powerfull pipe mechanism, pipe your own plugins (which may contain tons of fancy OO stuff)... and you can have great results while your code is still clean.
If you do think I am thinking too simple here, a good example of the essence of your point would be welcome! :-)
And to be ahead of that, if you are doing something really advanced and you do not get away with simply doing something on top of something else, you're plugin could also delegate to one of your OO classes. E.g. like:
$.fn.totalAwesomeness = function(options) {
var defaults = {
mode: 1,
title: 'Awesome'
};
var opts = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
var handler = null;
if(defaults.mode == 1)
handler = new com.myStuff.class1($this);
else if(defaults.mode == 2)
handler = new com.myStuff.class2($this); //class2 inherits from class1
handler.doMagic();
});
};
You can always also use moo4q - http://moo4q.com/ . It adds MooTools class support to jQuery.
I wrote an article some time ago about jQuery object oriented plugins, hope it will be helpful
http://ajax911.com/jquery-object-oriented-plugins/
There are third party javascript class implementations that provide very powerful introspection capabilites. I would like to particularly highlight JS.Class and Joose.
While JS.Class is modeled after Ruby, Joose is modeled after Moose.
I am not a mootools user so I can not comment on their advantages/disadvantages with respect to mootools. But I would summarize their key features.
JS.Class has a strong focus on simulating the Object oriented features of Ruby and does a pretty good job at that. It provides a powerful library modeled after the standard library of Ruby and also comes with a well integrated package management and testing framework.
Joose, while provides no testing framework/package management facilites, excels in terms of
advanced attribute management facilities, filters and better introspection facilities.
Both of them have really good documentation and can be used in browser as well as server.
I've just finished a very first release of my mini project: https://github.com/op1ekun/plOOgins. It's all about writing OOP code to be used as Jquery plugins. It's not rocket science just a little something that we wanted to use at my workplace. Maybe it will help You a bit. Good luck!
Plugins sometimes do the trick.
Of course, you could use just enough of mootools to get it's class/inheritance model. With the implementation of document.id "compatibility mode" in 1.2.3 you can have your cake and eat it too (I think--haven't done it myself.)
The question is... Why are you moving away from MooTools is it fits your needs? Seems to me like MooTools was working fine, and there is nothing jQuery does that MooTools can't do. (The opposite isn't true).
Unfortunately, jQuery is not built to support classical OOP as MooTools is so you will need to write your Classes as jQuery plugins.

Categories