Dojo Toolkit in a nutshell. Part 2.

In the part 2 of the Dojo Toolkit basic course, we will do the review on various aspects of working with this JS framework.

The Dojo Toolkit library in practice

The possibilities of the library already discussed in the first part, although the words are unnecessary when we revise examples.

Configuration

At the beginning — the Dojo configuration mechanism.

The dojoConfig object is the main mechanism Dojo configuration in our application / web page. In older versions this object was called djConfig — it’s outdated name, which we can meet in old codes based on the Dojo Toolkit.

Example of use — load the library with setting configuration parameters:

JavaScript

dojoConfig= {
    has: {
        "dojo-firebug": true // has (dojo-firebug sub-property)
    },
    // others
    parseOnLoad: false,
    foo: "bar",
    async: true
};

HTML

<script
  src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js">
</script>

This configuration must be defined before loading dojo.js, otherwise our settings will be ignored.

It should be noted the difference between dojo/_base/config and dojoConfig (it’s for determination of input parameters). In this way we “communicate” with the code involved in the loading of modules.

Dojo Toolkit in a nutshell. Part 1.

Dojo Toolkit is open-source collection for JavaScript programming language. It provides a rich set of tools for developers.

The Dojo Toolkit library

The framework includes a number of components.

Widgets (and the Dijit widgets system)

Dojo widgets are composed of JavaScript, HTML and CSS, and there are, among others: menus and tool-tips, sortable tables, dynamic charts and 2D vector graphics, animations, calendars, timers, form elements with validation procedures, etc.

Skins

You can use different skins to change the look of widgets / UI.

Asynchronous communication (client-server)

That is one of the most important capabilities of an application that uses AJAX, traditionally performed using XMLHttpRequest JavaScript.

Wrapper offered by Dojo (dojo.io.bind) allows the use of XMLHttpRequest in different browsers without changing the code. It supports also other methods of transportation (e.g. hidden iframes) and various data exchange formats.

Package system

Dojo offers a package system, so we can put the functionality in separate packages in a modular programming style. Furthermore, it is possible to define dependencies.

Storing data on the server side

In newer versions, the Dojo Toolkit supports data storages on the server side by dojo.data: CsvStore (CSV format), OpmlStore (OPML format), YahooStore, DeliciousStore, RdfStore (RDF).

Support for Adobe Integrated Runtime (AIR)

Dojo Toolkit can be safely used in applications based on Adobe AIR (updated safety rules).

Programming with Dojo Toolkit — quick start

The complete library can be obtained from the official website.

It can also be attached using a CDN, as the following example of a simple HTML5 page.

Introduction to Ext JS

Today’s course is little bit different. This is a one-piece mini-course of Ext JS library. It aims to introduce this powerful JavaScript framework.

The Ext JS

It’s a framework for JavaScript language, which supports building interactive web applications, user interfaces and more, using techniques such as DOM or AJAX.

Ext JS has among others many built-in controls of GUI, such as date-picker, HTML editor, controls for trees and grids, toolbars and menus in the style of desktop applications, sliders or charts based on vector graphics. And furthermore other advanced functionality.

A wealth of possibilities was presented briefly in demo examples.

You should, however, accept the license, because the library depending on purpose, is available on the Open Source or commercial license.

Starting with Ext JS

Get Ext JS from the official website.

It is also possible to take advantage of the CDN:

&amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot; charset=&amp;amp;quot;utf-8&amp;amp;quot;
  src=&amp;amp;quot;http://cdn.sencha.io/ext-4.2.0-gpl/ext-all.js&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/script&amp;amp;gt;

We test whether everything is as it should be:

Ext.onReady(function() {

  alert(&amp;amp;quot;Congratulations - Ext JS is loaded&amp;amp;quot;);

  // here we add the code based on Ext JS

});

In jQuery we have .ready event:

$(document).ready(function() {
// …
});

And we can see some similarity here. Ext JS has the Ext.onReady event, which determines that the library has been successfully loaded.

jQuery course — AJAX, examples, and a summary

Here we have the 3rd part of jQuery course.

Further exploring of jQuery possibilities

Today we briefly describe programming Ajax elements, using jQuery.

We show also some interesting examples and tips jQuery, and finally mention about jQuery UI.

The jQuery gives us a high level of abstraction, with a rich support for Ajax. So the programmer is is able to make final effect with a small amount of code.

A basic example — load file content:

$(document).ready(function() {
    $('#content').load('lorem.html');
});

To work with Ajax in jQuery, we use main methods: $.post(), $.get(), $.ajax().

Example — sending data to the server using the POST method and a simple callback:

$.post('save.cgi', {
    text: 'my string',
    number: 23
}, function() {
    alert('Your data has been saved.');
});

Example — getting data using $.get():

$('#letter-e a').click(function() {
    $.get('e.php', {'term': $(this).text()}, function(data) {
        $('#dictionary').html(data);
    });

    return false;
});

jQuery — DOM, events and effects. Part 2.

Here we go with the second part of jQuery basics, in which we describe the visual effects, DOM operations and events handling using this library.

Getting deeper in jQuery

Let’s start with the basics of visual effects.

There are main methods for elements visibility:

show() — causes dynamic showing of hidden element. As arguments can take a speed and the callback function:

show( speed, callback )

hide()  — hiding an element:

hide( speed, callback )

toggle() — toggle the visibility of the element: show — if hidden, hide — when visible:

toggle( switch )

Example — use the toggle() method on the button element:

var flip = 0;
$("button").click(function () {
    $("p").toggle( flip++ % 2 == 0 );
});

Folding and unfolding the element

These methods are able to change the visibility of an item, and they do it with animation (winding / unwinding):

slideDown( speed, callback )

slideUp( speed, callback )

Fading — transitions

In this case there is an animation of appearance / disappearance:

fadeIn( speed, callback )

fadeOut( speed, callback )

Change the style of element

We can dynamically set the element’s style, using methods: css(), addClass() and removeClass().

Examples:

$(this).css('color', 'yellow'); // set the color property
$(this).addClass('inny'); // add the CSS class
$(this).removeClass('inny'); // remove class

Example #2 — iteration:

$(document).ready(function(){
    // every li element will be blue
    $('li').css('color', 'blue');
});

Cascade

We know this already from other frameworks. Many methods can be linked together in a chain.

Example:

$('li').css('color', 'yellow').append('- read more')
    .css('background', 'black');
// of course we can call this as 3 separate instructions

Events and jQuery

Another very strong point of jQuery is the event handler.

jQuery course — basics

And now it’s time for jQuery!

jQuery course — basics of framework

Welcome to the 1st part of basic jQuery course. We talked already about various JavaScript frameworks (such as Prototype JS or MooTools).

Now we want to describe the key topics of a giant — jQuery.

Speaking giant, we mean the possibilities offered by this library. And for us, jQuery is preferred JavaScript / Ajax library.

The reason is simple — jQuery is popular and high-quality library, with extremely huge opportunities. If something is not offered by jQuery, probably there is at least one (usually much more) jQuery plugin(s).

Of course we can also create own plugins and publish them. In addition, jQuery has an excellent extension (jQuery UI). It is used to create and manage rich user interfaces for web applications.

Using jQuery in the project

Download the library from homepage.

It can also be added using CDN. In this example will always be included in the latest version:

<script src="//code.jquery.com/jquery-latest.js"></script>

We start with an important issue, which is noConflict.

Sometimes (fortunately perhaps less frequently than in the past) that the project uses several JavaScript libraries. And in many of them, as in jQuery, we can find e.g. the $() function. In such a case there is a threat of the conflict.

To avoid such a situation, jQuery introduces a method called noConflict (), which allows us to assign the full power of the $() to a variable, and wrap it separately.

Example:

var jq = jQuery.noConflict();

We can also insert code based on jQuery among another, e.g. based on Prototype JS, in a following way:

jQuery(document).ready(function($) {
    // here you can use $ of jQuery …
});

The extreme parameter — jQuery.noConflict(extreme) — the method has boolean parameter (extreme). In short, this parameter forces the assignment of $() functions to its original owners.

Example:

var dom = {};
dom.query = jQuery.noConflict(true);

JQuery selectors in a nutshell

JQuery gives us a set of powerful and useful selectors for elements.

Consider a practical example.

Retrieving an element of the type (the name as a parameter):

// $('p').click(function(){ … });

// add click handler to all paragraphs
$('p').click(function() {
    alert('Click');
});

Retrieving an element by ID (# as a prefix):

// get element with ID = 'content'
$('#content').click(function() {
    alert('Click click');
});

Getting elements by CSS class (a dot as a prefix):

$('.niceClass').click(function() {
    alert('Get by CSS class');
});

Retrieving by the value of an attribute. We can retrieve the elements by the value of any attribute.

E.g. for :

<a href="ipsum.html">ipsum</a>

we write:

$('a[href="ipsum.html"]').click(function() {
    alert('You clicked ipsum.html');
});

Child combinator:

// add the class for li elements of the 'selected-uls' parent
$(document).ready(function() {
    $('#selected-uls > li').
        addClass('horizontal-foobar');
});

Negation — not:

$('#selected-uls li:not(.horiz)').addClass('sub-level');

The specified condition will be negated.

MooTools library in a nutshell. Part 2 — summary.

Here is the second, summarizing part of the course, the theme of which is the JavaScript MooTools library.

The MooTools library

Let’s start with the benefits of object-oriented programming (OOP) support, offered by MooTools.

“Class” and creating classes

Constructor:

var MyClass = new Class(properties);

where: properties (object) — is a collection of class properties.

These properties can also be incorporated by Extends and Implements methods.

Example — the Class construction:

var Cat = new Class({
    initialize: function(name) {
        this.name = name;
    }
});

var myCat = new Cat('Kitty');
alert(myCat.name); // 'Kitty'

This is equivalent to creating classes. Whereas using Extends, we get the equivalent of inheritance.

Example — using Extends:

var Animal = new Class({
    initialize: function(age) {
        this.age = age;
    }
});

var Cat = new Class({
    Extends: Animal,
    initialize: function(name, age) {
        this.parent(age); // will call initalize of Animal
        this.name = name;
    }
});

var myCat = new Cat('Kitty', 20);
alert(myCat.name); // 'Kitty'
alert(myCat.age); // 20

If someone has programmed in object-oriented languages​​, where interfaces were available, and wants to try it in JavaScript, may have a look at “Implementes” from MooTools library.

Example — working with Implements:

var Animal = new Class({
    initialize: function(age) {
        this.age = age;
    }
});

var Cat = new Class({
    Implements: Animal,
    setName: function(name) {
        this.name = name;
    }
});

var myAnimal = new Cat(20);
myAnimal.setName('Kitty');
alert(myAnimal.name); // 'Kitty'

MooTools and inheritance

OOP support from MooTools helps to simulate inheritance, so ultimately useful in programming games, widgets, etc.

Let’s analyze the example:

var Human = new Class({
    initialize: function(name, age) {
        this.name = name;
        this.age = age;
    },

    isAlive: true,
    energy: 1,
    eat: function() {
        this.energy++;
    }
});

var Ninja = new Class({
    Extends: Human,
    initialize: function(side, name, age) {
        this.side = side;
        this.parent(name, age);
    },
     energy: 100,
     attack: function(target) {
         this.energy = this.energy - 5;
         target.isAlive = false;
     }
});

var bob = new Human('Bob', 25);
var blackNinja = new Ninja('evil', 'Nin Tendo', 'unknown');
// blackNinja.isAlive = true
// blackNinja.name = 'Nin Tendo'
blackNinja.attack(bob);

As you can see, in MooTools we can define ‘classes’ easy, and expand them by creating ‘child-classes’.

Elements

Time to say a few words about handling elements in MooTools.

First of all, we have well-known function $():

var myElement = $(el);

The $$() function

It retrieves items by the HTML tag name.

var myElements = $$(aTag[, anElement[, Elements[, …]);

MooTools in a nutshell. Part 1.

MooTools is another library, worthy of attention. It can also expand our view on the JavaScript language itself.

“My Object-Oriented Tools” — MooTools

It is modular (in construction) JavaScript library. The foundation is called Core.

Other libraries are optional. MooTools consists of a plurality of modules. Such design allows users to retrieve only the parts of the library, which they intend to use.

The implement method

Its goal is to extend the functionality of our native objects.

Example — implement method:

var Person = new Class({
    initialize: function(firstname) {
        this.firstname = firstname;
    }
});

Person.implement({
    sayHi: function() {
        alert('Hi ' + this.firstname);
    }
});

We can extend also in bulk:

Native.implement([obj1, obj2, obj3], {
    method1: function() {
        // (…)
    },
    method2: function() {
        // (…)
    }
});

More about the Core

It offers many possibilities:

$chk() — checking objects:

function myFunction(arg) {
    if ($chk(arg))
        alert('The object exists or is 0.');
    else
        alert('The object is either null/undefined/false');
}

$clear()  — cleans timeout / interval:

// execute myFunction in 5 sec
var myTimer = myFunction.delay(5000);
myTimer = $clear(myTimer); // cancels myFunction

$defined(obj)  — checks whether the value is defined, for example:

$defined(document.body); // true

$arguments() — creates a function that returns the argument depending on the index:

var secondArgument = $arguments(1);
alert(secondArgument('a','b','c')); // "b"

$empty() — empty function (mockup):

var myFunc = $empty;

$lambda() — creates an empty function that returns the passed value:

var returnTrue = $lambda(true);

// prevents a link Element from being clickable
myLink.addEvent('click', $lambda(false));

It is outdated method. Currently recommended to use Function.from.

Script.aculo.us library in a nutshell. Part 2 — summary.

The 2nd part of the script.aculo.us library course. Today about its strongest point — visual effects.

Getting to know more possibilities of script.aculo.us

Visual effects

Effects have their own options, but everywhere we can use Core Effect properties.

The general form:

new Effect.EffectName(element, required-params, [options]);

Let’s see how it looks in practice.

Example — use effects:

<div id="morph_demo" style="background: #ccc; width: 100px; height: 100px;"></div>
<ul>
  <li>
    <a href="#" onclick="$('morph_demo').morph('background: #00ff00; width: 300px;'); return false;">
    Click …
    </a>
  </li>
  <li>
    <a href="#" onclick="$('morph_demo').morph('background: #cccccc; width: 100px;'); return false;">
    Reset
    </a>
  </li>
</ul>

Example #2 — determination of the effect parameters:

HTML

<div id="our_div" style="background: #eee; width: 100px; height: 100px; border: solid 2px red;"></div>

JavaScript

new Effect.Opacity('our_div', {
    duration: 2.0,
    transition: Effect.Transitions.linear,
    from: 1.0,
    to: 0.2
});

The above code defines the effect of changing the transparency for the our_div element.

Common callback functions

These are:

– beforeStart()

– beforeSetup()

– afterSetup()

– beforeUpdate()

– afterUpdate()

– afterFinish()

Effects: properties and methods

For the Effect object instances, there are a number of useful properties and methods, such as:

– effect.element — element to which the effect is applied

– effect.options — contains options defined for effect

– effect.currentFrame — the last rendered frame number

– effect.startOn, effect.finishOn — determine the time (ms) when the effect will be started / stopped

– effect.effects[] — an array containing the definitions of the individual effects (for Effect.Parallel)

– effect.cancel() — stopping the effect

– effect.inspect() — returns basic information about the instance (debug)

Example — simple animation:

new Effect.Move(this, {
    x: 200,
    transition: Effect.Transitions.spring
});

Effect queues

This is an excellent possibility offered by the library, allowing us to queue and perform many effects as a sequence.

Example — queue effects:

new Effect.SlideDown('test1');
new Effect.SlideUp('test1', { queue: 'end' });

// 2
new Effect.SlideUp('test1', { queue: 'end' });
new Effect.SlideDown('test1', { queue: 'front' });

// 3
new Effect.SlideUp('menu', { queue: { position: 'end',
    scope: 'menuxscope' } });

new Effect.SlideUp('bannerbig', { queue: { position: 'end',
    scope: 'bannerscope' } });

new Effect.SlideDown('menu', { queue: { position: 'end',
    scope: 'menuxscope' } });

Course: script.aculo.us library in a nutshell — part 1

The script.aculo.us library

Delving into the JavaScript frameworks, we would like to present the essence of script.aculo.us library.

As we mentioned in JS Frameworks introduction, Prototype JS and script.aculo.us libraries are often seen together.

The library, which now referred to, is like an extension of Prototype JS of visual effects, animation, Drag and Drop, creating widgets, tools for working with DOM, or Ajax controls. Functions of this library are easy to use, and of course there are cross-browser.

Working with script.aculo.us library

At the beginning we add Prototype JS and script.aculo.us to the document. Let’s start with a few words about how to create dynamic elements.

Component that supports the creation of DOM elements is the Builder, fulfilling the function of pattern.

Example — using the Builder component:

var tbl = Builder.node("tbl",
    { border: 0, width: 200 },
    [ Builder.node( "tr", [
        Builder.node("td", {width: 100}, "column 1" ),
        Builder.node("td", {width: 100}, "column 2" ),
        Builder.node("td", {width: 100}, "column 3" )
    ])
]);

$('mydiv').appendChild(tbl);

Example #2:

var element = Builder.node('div', { id: 'ghosttrain' }, [
    Builder.node('div',
        { className: 'controls', style: 'font-size:11px;' },
        [
        Builder.node('h1', 'Ghost Train'),
        'testtext', 2, 3, 4,
        Builder.node('ul', [
            Builder.node('li', { className: 'active',
                onclick: 'test()' }, 'Record')
        ]),
    ]),
]);

Drag&drop support

Script.aculo.us allows us to quickly implement Drag and Drop, and add eye-catching animations.

The library provides for this purpose following classes:

Draggable — defines an object that we will drag,

Droppables — allows to design an appropriate response for dropping the item.

The Draggable class

That means elements, which can be dragged.

Example — Draggeble test:

var test = Builder.build("<span>Displacement</span>");

document.getElementsByTagName("body")[0].appendChild(test);
new Draggable(test);
new Draggable('id_of_element', [options]);

More details about this class you can find here.

Example #2 — Draggable — settings:

new Draggable('mydiv', { constraint: 'horizontal',
    handle: 'handle' });

var mydrag = new Draggable('dv1', { revert: true });
mydrag.destroy();

// assignment back
// new Draggable('dd1', { revert: true });
new Draggable('dd1', { revert: true, snap: [40, 40] });

new Draggable('dd2', { scroll: window });

The Droppables class

So elements that can be dropped.

Example — using Droppables:

Droppables.add('id_of_element',[options]);

Droppables.add('shopping_cart', {
    accept: 'products',
    onDrop: function(element) {
        $('shopping_cart_text').
            update('Dropped the ' + element.alt + ' on me.');
    }
});

Droppables.remove(element); // removing

Example — all the elements of the list as Draggable:

$$('container li').each( function(li) {
    new Draggable(li);
});

And now we can drag items of the list.