Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Monday, January 10, 2011

Using jQuery JavaScript library in Oracle ADF Faces (JDeveloper) application

Why jQuery and ADF Faces?

jQuery (as we all know) is quite useful js library and you can do amazing things with it. Oracle ADF Faces (which is based on Apache MyFaces Trinidad JSF library) is very useful and future rich JSF implementation. But, there are times when you do not want to follow all ADF framework bits and pieces and just solve your problem by programing stuff on client side using JavaScript and jQuery.

Steps

Off course, first download jQuery from jQuery site (I prefer non compressed version, because we are using ADF Faces mainly for application inside firewall and with high bandwidth).

Then create lib folder in your ADF application (inside View Controller Project in Web Content folder). Put jQuery library there.

If you want to use have access to jQuery library in all your jspx pages then put following tag in you template (before af:pageTemplateDef):


 

In this way you load jQuery js library from real path (using request object).

If you want to include jQuery in single page (jspx) then use af:resource (inside af:document) like so:


  
    
  


Using metaContainer facet and af:group is recommended Oracle method for loading js libraries.

Finding components

For finding specific ADF components (or plain simple HTML components), you can use id property from ADF components or you can use class attributes that are defined by ADF Faces.

It can be little tricky to find specific component (because ADF faces is not so simple on browser end), but tools like firebug can help you by identifying specific component and show it's name or id value.

Friday, December 24, 2010

Creating complete jQuery plugin

Introduction

jQuery promote writing reusable components as jQuery plugins. This is good practice and a smart way of working. Also jQuery promotes a certain style for writing these plugins. This short example is simple guideline that show how to do this.

Example

You can download simple example (that include complete Java web application and jQuery plugin that uses Ajax) from my google code repository.

This example is composed of single JSP page that show programming languages names and by clicking on some language we get description of that language in the bottom of page by pulling it from server using Ajax.


1.Naming conventions.

The recommendation is simple: prefix the file name with jQuery, then follow that with the name of the plugin, optionally include version number of the plugin, conclude it with .js.

We named our plugin "details" (because it show details about some programming language, I know it's stupid...but what can you do! :) ) and we named file jquery.cwp.details.js. Here we added unique plugin name to our self (cwp stands for "coding with passion") and limiting name conflict problems.

Similar consideration need to be taken with the names we give to our function. In our case we did not bother with that because there is 100% chance that this plugin will be used by me and only me and I probably will never use it again (outside of this example)...so there you go.

2.Handle $ alias properly.

We have no way of knowing weather a web developer (using out plugin) use $.noConfilct() function to allow the $ to be used by another library, so we need to guard ourself for such situation. We can use following trick to do so:

(function($) {
  //plugin impl.
  })(jQuery);

By passing jQuery to a function that defines the parameters as $, $ is guaranteed to reference jQuery within the body of the function.

3.Complex parameter list.

Most plugins tend to be simple affairs that require few, if any, parameters. Intelligent defaults are supplied when optional parameters are omitted. The bind method is a good example; it the optional parameters are omitted, the listener function, which is normally specified as the third parameter can be supplied as the second.

We can use handy $.extend function to merge default parameter with optional. Consider the following show example:

function complex(p1, options) {
  var settings = $.extend({
    option1 : defaultVal1,
    option2 : defaultVal2,
    option3 : defaultVal3
  }, options||{});
  //"meat" of the function.
}

By merging the values passed by the web developer in the options parameter with an object containing all the available options with their default values, settings variable ends up with the default values superseded by any explicit values specified by the developer.

Note: With options||{} we guard ourself against options object that is null. or undefined.

4.Wrapper methods.

The true power of jQuery in the ability to easily and quickly select and operate on DOM elements. Luckily, we can extend that power by adding wrapper methods of our own. The general pattern of doing so is:

$.fn.functionName = function(params){function-impl};

That is almost it, just remember to always return (this) for chaining support. All that said, here is our function in all its glory :) :

(function($) {
    $.fn.details = function(url, options) {
        var settings = $.extend({
            customClass: null,
            paramName: 'language',
            url: url
        }, options||{});
        this.click(function(event) {
            $('div.details').remove();
            //substitute lt with appropriate start tag and gt with end tag...
            $('lt div gt')
            .addClass('details' +
                (settings.customClass ? (' ') + settings.customClass : ''))
            .css({
                display: 'none'
            })
            .appendTo('body')
            .load(settings.url,
                encodeURIComponent(settings.paramName) + '=' +
                encodeURIComponent($(event.target).text()),
                function() {
                    $(this).closest('.details').fadeIn('slow');
                });
        })
        this.addClass('details');
        return this;
    };
})(jQuery);

Monday, December 13, 2010

Ajax tutorial with jQuery

Introduction

AJAX is just simple technique for refreshing browser DOM with data acquired from some kind of server (Servlet/JSP, PHP, ASP.NET, ...). There is nothing specially clever in this technique.

Ajax is a less recent addition to the web toolbox than many people may realize. In 1998, Microsoft introduced the ability to perform asynchronous request as an ActiveX control (part of Outlook Web Access ).

After few years MS browser introduced standardized XMLHttpRequest (those days everything was flavored with XML :) ) object. These days you will not use XML with AJAX requests (rather JSON, or simple HTML). Google coined the term AJAX (Asynchronous JavaScript and XML -- you see!) and rest is history.

You can download example from this tutorial from my google app code SVN repository.

Plain JavaScript VS jQuery

Using plain JavaScript to implement AJAX (all cross browser JavaScript stuff) is not so easy. In a perfect world, code written for one browser would work in all commonly used browsers. But we do not live in perfect world and in this situation IE is one browser that handle AJAX in different way. The main problem is to create and instance of XMLHttpReauest object.

Let I give you some quick insight what you need to do in other to (just) get instance of this object in plain (cross browser) JavaScript:

var xhr;
if (window.ActiveXObject) {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else  if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
}
else {
  throw new Error("This browser is not ajax enabled.");
}

There are couple of things you need to consider when you handle AJAX using plain JavaScript. One is encoding, another is creating handler for response...and so on.

Now, the jQuery code for AJAX request and getting response is as follows:

$('#driverSelectionControl').load('/AjaxExampleCWP/actions/driversList.jsp');

I think we have a winner! So we will be using jQuery from now on and leveraging it great capabilities.

jQuery load() method

Perhaps the most common uses of Ajax is to grab a chunk of content from the server and stuff it into the DOM as some strategic location. jQuery do just that, it's "load" html code into wrapper set using (go figure!) load() method. It sound simple and it is simple!

Let's go straight to the example:

We have page select component with F1 race drivers names filled in. When you change driver name, his details will be pulled from server and appended to DOM without page refresh. Interesting detail in this example is that select HTML component is also populated using Ajax.

Code for initial page DOM:


Now I will show you code for Ajax stuff and explain afterwards.

$(function() {
  $('#driverSelectionControl').load('/AjaxExampleCWP/actions/driversList.jsp');

    $('#driverSelectionControl').change(function(event) {
      $('#driverDetailPanel').
        load('/AjaxExampleCWP/actions/driversDetails.jsp',
             {driverId : $(event.target).val()});
    });
});

02: Loading options html components into select component. You see how easy is to use Ajax with jQuery! :) We just need to give URL to JSP page.

Here is JSP page for driver list:






That's it. All that this JSP page do is rendering options components.

04-08(from previous example): Here we handle change event. When user select another driver (value is changed), then we load his detail from driversDetails.jsp. We pick user by passing parameter (driverId) to JSP page.

Here what JSP page look like:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    
        
        
        
        
        
    
    
        
        
        
        
        
    
    
        
        
        
        
        
    


Driver name ${item.name}
Team name ${item.team}
Podiums ${item.podiums}
Points ${item.points}
Date of Birth ${item.birth}

You can use POST (default) or GET HTTP request method using load method. If you want to use POST (like in this example) then you send object hash as parameter to load (for example: {driverId : 205} ). If you want to initialize GET request, then you need to pass query string. If you use GET, you must ensure that your string is properly formated (names and values are URI-encoded).

If you are wondering when to use POST and when to use GET then follow this recommendations:

Use GET request when request operation that is made again and again make no change to state of server (for example when you just pulling data from server). This mean that our example is in opposite to this recommendation!
Use POST request when operation your request is initiating is non-idempotent (as opposite to idempotent like in GET). This mean, that you should use POST when you change some state on server (changing, or updating the data).

Other jQuery Ajax methods

jQuery include other methods for Ajax functionality like $.get(), $.post() for explicit GET or POST request operations.

jQuery also provides a general utility function for making Ajax requests, named $.ajax(). Under the covers, all other jQuery features uses this function. It it quite powerfull, but also complex. Feel free to investigate this function if you are interested.

Saturday, November 20, 2010

Dynamically loading new script into page using jQuery

We mostly load external script files in our page using script src tag. But now and then, we need to load JavaScript file under script control. There are couple of use cases for this:


  • We don't to load file at runtime (because of some restriction, or because of file size);
  • or maybe we need to execute some condition before decide which file we will load.
jQuery provide <b>$.getScript()</b> utility function to enable this functionality. This function uses jQuery Ajax functions to fetch this file. 

Ok, let's see how it works!


Following code represent external JavaScript file (named: new_script.js).
$('#console').html("Script is loaded...");
function dragonBallFunction(value) {
    alert(value);
}

On page we have defined two buttons. First button load script file, second execute function from external file that first loaded.

As you can see it is quite simple:

$(function() {
    $('#loadButton').click(function() {
        $.getScript("new_script.js");
    });
    $("#executeButton").click(function() {
        dragonBallFunction('Piccolo is not saiyan!\n::Goku:: is!');
    });
});

//normal html stuff 


Wednesday, September 29, 2010

jQuery triggering custom event (Observer pattern)


Introduction

We all know what basic events in JavaScript and jQuery are. They represent handlers that are triggered at specify event (click, timer, mouse move, etc.). But how do we create custom events that are triggered on our command, here comes jQuery to the rescue! Also doing this (calling custom events), we can simulate classic Go4 observer pattern (publish/subscribe).

Using jQuery is beneficiary, because, we are not concerned about various DOM levels, browser specific stuff (like: (event.target) ? event.target : event.srcElement;...), does IE 6,7,8 support event capture phase, and stuff like that. We basically create another abstraction level over various JavaScript implementations.

So, let the fun begin!

Live event handling

In our example we will use jQuery ability to manage event handler on the fly (as we manipulate the DOM by adding or removing elements). This means that we will proactively establish event handlers for elements that don't exist yet. jQuery provide this functionality with the live() method. Syntax for this method is similar like bind() or for example click() method.

Triggering events

In out example we will also need some method that will automatically invoke (trigger) event handlers on our behalf under script control. For this we will use the trigger method. This method does its best to simulate the event to be triggered. One curiosity is that it even populate instance of jQuery event (event object in jQuery style :) ), but because there is no real event, properties that report event-specific values such as the location of mouse x and y cordinates, have no value. Ok, let's move on.

Example

First jQuery part:

$(function() { //Wait until DOM is fully loaded .
    $('#addBox').click(function() {
        $('td.box:first-child').clone().appendTo('tr.boxLine');                
    });

    $('#paintBlue').click(function() {                
        $('td.box').trigger('paintThem');
    });

    $('td.box').live('paintThem', function() {
        $(this).css('background', 'blue');                
    });            
});

2-5: First we create simple click handler that add new box like element on the DOM. We create boxes using simple table and just adding new table data elements by coping them. Please see html part, and first picture where we add couple of boxes.

6-8: Here we trigger custom event named "paintThem". This is simple click event triggered by button. We need to trigger custom event on elements (in this case 'td.box') that posses custom event (but, also we can trigger standard events like: click, hover...).

10-12: The "real meat" of this whole story. Here we see a use of the live() method to proactively establish event handlers. The 'td.box' elements will be added dynamically to the DOM and live method will automatically establish handlers as necessary.
This way, we sat it up _once_ and jQuery will handle the details whenever an item that matches that selector (td.box) is create (or destroyed). Great stuff!

So as you can see, this example is not so fancy, it just paint red boxes to blue. But the way it does it is interesting. I can also walk trough all elements and paint them to certain color, but this approach is much cleaner and in some situations better (asynchronous refresh (AJAX) for example).

Then, html part. My apologies for this fuzzy looking html code (it's blogger fault! :) ).


Custom event is a very useful concept. Using it, we can attach code to an element as a handler for a custom event, and cause it to execute by triggering the event. The beauty of this approach, as opposed to directly calling code, is that we can register the custom handlers in advance, and by simply triggering the event, cause any registered handlers to be executed, without having to know they've been established.

Custom event concept in jQuery can be seen as limited version of Observer pattern. In this pattern (also know as publish/subscribe pattern) we subscribe an element to a particular event by establishing a handler for that element, and then when the event is published (triggered), any elements that are subscribe to that event will automatically invoke their handlers.

In this way we are creating loose coupling (and that is always a _good_ idea) in our JavaScript code. This make our code cleaner and meaner!

Custom trigger in action:

Adding boxes.


Triggering event to paint boxes in blue.