Saturday, 6 October 2012

jQuery Vs AUI(Alloy UI)

Getting Started

jQuery AUI Notes
$.change.bar()
AUI().use('node', 'module2', 'module3', function (A) {
  A.change.bar()
});
The jQuery and $ objects are globals and the jQuery library itself is statically loaded, so they are available immediately.
AUI is sandboxed and by default dynamically loaded. The A object is local to the function you pass as the last argument to AUI().use(). Usually you will put all code that uses AUI inside one of these functions. This function executes after all the referenced modules are loaded and accounted for.
The return value of AUI().use() is also a A object, which you can assign to a global variable [e.g. var A = AUI().use(…);] and debug with it in a JavaScript console.

Common Idioms

jQuery AUI Notes
$('div.change:first')
A.one('div.change')
jQuery and AUI use similar selector syntax, but jQuery has added extensions, mainly convenience pseudo-classes, to the Sizzle CSS3-compliant selector engine. AUI comes with three different selector engines; see the section on Selectors.
var change = $('div.change:first');
change.some_method();
var change = A.one('div.change');

if (change) {
  change.some_method();
}
Return the first element which matches the selector. :first is a jQuery extension.
If no elements match, A.one() returns null and you should check for it. jQuery selector methods always return a list object with 0 or more elements.
$('div.change')
A.all('div.change')
Select all div elements with a class of change.
var change = $('div.change');

if (change.length) {
  // do something
}
var change = A.all('div.change');

if (change.size()) {
  // do something
}
If no elements match the selector, A.all() returns an empty NodeList object. jQuery will return an empty list [] that is loaded with special jQ methods. Both are truthy even if they contain no elements, so use NodeList.size() and [].length to check for emptiness.
.find('p.change:first')
.find('p.change')
.one('p.change')
.all('p.change')
Finds P elements with class change that are children of the given node.
$('<div/>')
A.Node.create('<div/>')
Create a new DOM element. Does not add it to the document tree.
.html('change')
.text('change')
.val('change')
.html('change')
.set('text', 'change')
.set('value', 'change')
.set() is a generic method in AUI for modifying element object properties. Use .setAttribute() to modify element attributes..html(html) is a convenience wrapper around .set('innerHTML', html)
.html()
.text()
.val()
.getHTML()
.get('text')
.get('value')
jQuery tends to overload getters and setters in the same method.
.attr('change')
.attr('change', 'bar')
.getAttribute('change')
.setAttribute('change', 'bar')
Generic HTML attribute getters and setters.
$.trim(' change ')
A.Lang.trim(' change ')
Strips leading and trailing whitespace.
.click(fn)
.focus(fn)
.blur(fn)
.mouseout(fn)
.mouseover(fn)

// jQuery   and later allows you to
// register events when creating the element
$('<p/>',{
  text      :'change',
  className : 'bar',
  click     : fn,
  focus     : fn,
  blur      : fn
})
.on('click', fn)
.on('focus', fn)
.on('blur', fn)
.on('mouseout', fn)
.on('mouseover', fn)

// Alternatively, AUI allows you to attach multiple
// subscribers with a single call.
.on({
  click    : fn,
  focus    : fn,
  blur     : fn,
  mouseout : fn,
  mouseover: fn
})

// Or attach a single subscriber to multiple events.
.on(['click', 'focus', 'blur', 'mouseout', 'mouseover'], fn)
.on() is not chainable by default, but multiple subscribers can be attached in one call using the syntax shown here.
$('#change').trigger('click')
A.one('#change').simulate('click')
Simulates a click event. In AUI, you'll need the node-event-simulate module.
parent.append('<div/>')
parent.append('<div/>')
Creates a new div element and makes it a child of parent.
child.appendTo(parent)
child.appendTo(parent)
Appends child to parent, and returns child.
.appendTo() was added to AUI in 3.3.0.

parent = $('<div/>');
$('<p>change<p>')
  .click(fn)
  .appendTo(parent);
parent = A.Node.create('<div/>');
A.Node.create('<p>change</p>')
  .appendTo(parent)
  .on('click', fn);
Creates a new div element, then appends a p element with a click event subscription. Note that AUI's on() method is not chainable, so it returns an event handle, not the p node.
// Removes #change from its parent and
// detaches events and jQuery data.
$('#change').remove()

// Removes #change from #container.
$('#container').remove('#change')
// Removes #change from its parent, but doesn't
// detach events or AUI plugins.
A.one('#change').remove()

// Removes #change and detaches events and plugins.
A.one('#change').remove(true)

// Removes #change from #container.
A.one('#container').removeChild(A.one('#change'))
jQuery's .remove() purges events and jQuery data from the removed node. For the equivalent behavior in AUI, use .remove(true).
.empty()
.empty(true)
jQuery's .empty() also deregisters any events associated with the elements being destroyed. Passing true to .empty() enables the same behavior in AUI.

.empty() was added to AUI in 3.3.0.


.siblings()
.siblings(selector)
.siblings()
.siblings(selector)
.siblings(function)
In addition to an optional selector string, AUI also supports passing a function to filter the returned siblings.
.next()
.next(selector)
.next()
.next(selector)
.next(fn)
Same considerations as .siblings().
.prev()
.prev(selector)
.previous()
.previous(selector)
.previous(fn)
Same considerations as .siblings().
.parent()
.get('parentNode')
Returns the parent node of the given node.
.children()
.get('children')
Returns all the element children of the given node.
.closest(selector)
.ancestor(selector)
.ancestor(fn)
Returns the first ancestor that matches the given selector. In addition, AUI supports using a function instead of a selector to find an ancestor.
$.contains(node, descendant)
.contains(descendant)
Check to see if a node contains a certain descendant.
.show()
.hide()
.show()
.hide()
Make DOM nodes appear/disappear
.fadeIn()
.fadeOut()
.show(true)
.hide(true)
In AUI, .show() and .hide() can be customized to use transitions supported by the transition module. These methods were added to AUI in 3.3.0.
$.parseJSON( '{"name":"Douglas"}' )
A.JSON.parse( '{"name":"Douglas"}' )
Converts a JSON string into an object. Requires the json-parse module.

A.JSON.stringify({name: "Douglas"})
Converts an object to a JSON string. Requires the json-stringify module. No jQuery equivalent.
$.proxy(fn, context)
A.bind(fn, context)
Creates a new function that will call the supplied function in a particular context.
.data(key)
.data(key, value)
.getData(key)
.setData(key, value)
Stores data associated with a DOM element without modifying the DOM.
.removeData()
.removeData(key)
.clearData()
.clearData(key)
Removes the associated data.

Selectors

jQuery AUI Notes
$('*')
A.all('*')
Select all nodes. Note that the default selector engine for AUI is CSS 2.1. For all examples in this section, use the selector-css3 module for AUI.
$(':animated')

Psuedoclass to select all elements currently being animated. No AUI equivalent.
$(':button')
A.all('input[type=button], button')
Extension. In both jQuery and AUI you can run multiple selectors separated by commas.
$(':checkbox')
A.all('input[type=checkbox]')
Extension.
$(':checked')
A.all(':checked')
CSS3
$('parent > child')
A.all('parent > child')
Immediate child selector (child must be one level below parent)
$('parent child')
A.all('parent child')
Descendent selector (child can be at any level below parent)
$('div.class')
A.all('div.class')
Class selector
$(":contains('change')")
A.all(':contains(change)')
Extension to select all elements whose text matches 'change'. jQuery can take quotes or not. AUI requires no quotes. The text matching is plain string comparison, not glob or regexp. Be careful with this one as it will return all matching ancestors, eg [html, body, div].
$(':disabled')
$(':enabled')
A.all(':disabled')
A.all(':enabled')
CSS3. 'input[disabled]' and 'input:not([disabled])' also work in both libraries.
$(':empty')
A.all(':empty')
CSS3. Selects all elements that have no child nodes (excluding text nodes).
$(':parent')
A.all(':not(:empty)')
Inverse of :empty. Will find all elements that are a parent of at least one element. jQuery's version is an extension. AUI's is CSS3.
$('div:eq(n)')
A.all('div').item(n)
Extension. Selects nth element. AUI's item() will return null if there is no nth element. jQuery's selector will return an empty list [] on a match failure.
$('div:even')
$('div:odd')
A.all('div').even()
A.all('div').odd()
Extension. Selects all even or odd elements. Note that elements are 0-indexed and the 0th element is considered even. See also AUI's NodeList.modulus(n, offset).
$(':file')
A.all('input[type=file]')
Extension. Find input elements whose type=file.
$('div:first-child')
A.all('div:first-child')
CSS3. Selects the first child element of divs.
$('div:first)
A.one('div')
The .one() method returns null if there is no match, and a single Node object if there is.
$('div:gt(n)');
$('div:lt(n)');
// or
$('div').slice(n + 1);
$('div').slice(0,n);
A.all('div').slice(n + 1);
A.all('div').slice(0, n);
Extension. :gt (greater than) selects all elements from index n+1 onwards. :lt (less than) selects all nodes from 0 up to n-1.
$('div:has(p)')
var nodes = [];

A.all('div').each(function (node) {
  if (node.one('p')) {
    nodes.push(node);
  }
});

nodes = A.all(nodes);
Extension. Selects elements which contain at least one element that matches the specified selector. In this example, all div tags which have a p tag descendent will be selected.
$(':header')
A.all('h1,h2,h3,h4,h5,h6')
Extension. Selects all heading elements. Rarely used.
$('div:hidden')
var hidden = [];
A.all('div').each(function(node) {
    if ((node.get('offsetWidth') === 0 &&
        node.get('offsetHeight') === 0) ||
        node.get('display') === 'none') {
        hidden.push(node);
    }
});
hidden = A.all(hidden);
Extension. In jQuery > 1.3.2 :hidden selects all elements (or descendents of elements) which take up no visual space. Elements with display:none or whose offsetWidth/offsetHeight equal 0 are considered hidden. Elements with visibility:hidden are not considered hidden.
The AUI equivalent would essentially be a port of the jQuery code that implements :hidden. This might be a good candidate for a patch to AUI.
$('#id')
A.all('#id')
CSS3. Identity selector.
$('input:image')
A.all('input[type=image]')
Extension. Selects all inputs of type image.
$(':input')
A.all('input,textarea,select,button')
Extension. Selects all user-editable form elements.
$(':last-child')
A.all(':last-child')
CSS3.
$('div:last')
var list = A.all('div'),
    len  = list.size(),
    last;

if (len) {
  last = list.item(len - 1);
}
Extension. Selects the last element matched by the selector.
$('input[type=checkbox][checked]')
A.all('input[type=checkbox][checked]')
CSS3, multiple attribute selector
$(':not(div)')
A.all(':not(div)')
CSS3. Negation selector.
$(':password')
A.all('input[type=password]')
Extension.
$(':radio')
A.all('input[type=radio]')
Extension.
$(':reset')
A.all('input[type=reset]')
Extension.
$(':selected')
A.all('option[selected]')
Extension.
$(':submit')
A.all('input[type=submit]')
Extension.
$(':text')
A.all('input[type=text]')
Extension. Does not select textarea elements.

Effects

jQuery AUI Notes
$('#change').animate(
  {
    width:   100,
    height:  100,
    opacity: 0.5
  },
  {
    duration: 600,
    easing:   'swing'
  }
);
var a = new A.Anim(
  {
    node: '#change',
    to: {
        width:   100,
        height:  100,
        opacity: 0.5
    },
    duration: 0.6,
    easing:   A.Easing.bounceOut
  }
);
a.run();
The basic syntax and capabilities of both animation libraries are very similar. jQuery has convenience methods for effects like .fadeIn(), .slideUp(), etc. jQuery core has two easing functions: 'linear' and 'swing', but jQuery UI comes with many more effects as plugins.
AUI has several easing algorithms built-in, and offers additional tools such as animations over Bezier curves. Make sure to load the 'anim' module in your call to AUI().use().
$('#.change').fadeOut();

// or

$('#.change').hide(600);
A.one('#change').hide(true)
jQuery's .fadeOut() fades the opacity to 0, then sets display:none on the element. .fadeIn() is naturally the inverse. The AUI equivalents are .hide(true) and .show(true) (note that the transition module must be loaded in order to get the fade effect).
jQuery effects tend to default to 200 or 600ms while AUI's show/hide transitions default to 500ms. AUI durations are in fractions of seconds; jQuery durations are set in milliseconds.

Array vs. NodeList

jQuery AUI Notes
$('.change').array_method(args)
A.all('.change').array_method(args)
Any Array operation that you can perform on a jQuery list can be translated to AUI in this form. AUI NodeList objects are not native Arrays, but do provide wrapper functions for the most common array methods as of 3.3.0.
$('div').slice(x, y)
A.all('div').slice(x, y)
Return the xth to the yth div elements.
$('div').add('p')
A.all('div').concat(A.all('p'))
Add nodes that match the specified selector.
$('.change').each(
  function() {
    $(this).some_method();
  }
);
A.all('.change').each(
  function() {
    this.some_method();
  }
);
.each() is like the for loop. AUI's each() returns the original NodeList to help with chaining.
$('.change').filter('.bar')
A.all('.change').filter('.bar')
The .filter() method in both libraries both take CSS selectors as filter criteria. jQuery's .filter() can also take a function.
$('.change').filter(function (idx) {
  return this.property === 'value';
});
A.all('.change').filter(function (node) {
  return node.get('property') === 'value';
});
Classic functional programming filter function. Given a list of elements, run the function on each and return a list of those which evaluated true.
$('.change').map(
  function(idx, el) {
    return some_function(el);
  }
)
var mapped = [];
A.all('.change').each(
  function (node) {
    mapped.push(some_function(node));
  }
);
mapped = A.all(mapped);
jQuery's .map() returns a jQuery-wrapped array of the return values of calls to the given function.

Ajax

jQuery AUI Notes
$.ajax({
  url:      url,
  data:     data,
  success:  successFn
});
A.io(url, {
    data: data,
    on:   {success: successFn}
});
AUI.io has extra options for failure mode callbacks, headers, cross-frame i/o, etc. jQuery.ajax() has some interesting options for async, context, and filtering. Make sure to load the AUI 'io' module.

A.io(url, {
    data: data,
    on:   {success: successFn},
    xdr:  {use: 'flash'}
});
Cross-domain requests via a Flash helper. No jQuery equivalent.
$('#message').load('/ajax/test.html');
A.one('#message').load('/ajax/test.html');
A.one('#message').load('/ajax/test.html', '#change');
Load the content of a given URL and replace the contents of #message with it.
In AUI, the node-load module provides this functionality. AUI also optionally supports extracting only a portion of the loaded content if a selector string is passed as the second argument (assuming the content is HTML).

CSS

jQuery AUI Notes
.addClass('change')
.removeClass('change')
.toggleClass('change')
.hasClass('change')
.addClass('change')
.removeClass('change')
.toggleClass('change')
.hasClass('change')
CSS class name manipulation.
.removeClass('change').addClass('bar')
.replaceClass('change', 'bar')
Replace node's CSS class 'change' with 'bar'.
.css('display', 'block')
.setStyle('display', 'block')
Set a single CSS property
.css({
    height:  100,
    width:   100,
    display: 'block'
})
.setStyles({
    height:  100,
    width:   100,
    display: 'block'
})
Set multiple CSS properties with a dictionary.
.css('display')
.getStyle('display')
Get the current value for a CSS property.
.height()
.width()
.getComputedStyle('height')
.getComputedStyle('width')
Computed height / width. Excludes padding and borders.
.innerHeight()
.innerWidth()
.get('clientHeight')
.get('clientWidth')
Includes padding but not border
.outerHeight()
.outerWidth()
.get('offsetHeight')
.get('offsetWidth')
Includes padding and border
.offset()
// {left: 123, top: 456, width: 789, height: 1011}
.getXY()
// [123, 456]
Get the computed x,y coordinates relative to the document. jQuery also returns the size of the node
.offset({ left: 123, top: 456 })
.setXY(123, 456)
Set the x,y coordinates relative to the document.

2 comments:

  1. Its really helpful for developer who are utilizing AUI feature of liferay while developing.

    ReplyDelete
  2. thats an awesome comparison sheet... thanks Tapas.

    ReplyDelete