Saturday, November 6, 2010

Finding elements using jQuery - Part 3

In this part of the series, I will be discussing a few more ways that are offered by jQuery to traverse siblings of an element.

The methods that we are going to discuss in this post are

prev()
prevAll()
prevUntil()
next()
nextAll()
nextUntil()

All these functions provide us with a way to traverse the siblings of a given DOM element. Lets see some examples.

  • 0
  • a
  • b
  • c


The prev() function selects the DOM element that lies immediately above the current element. So, if we were to apply the prev function to our list item3, it would select the list item 2. However, if you want to select the previous item only if it matches a particular criteria, then you can pass a selector to the prev() function. Note tat the selector function DOES not select the first matching previous sibling. Instead it first select the previous sibling, and then applies the test criteria to it.

$(".item3").prev().addClass("highlighted");

The above code would select the second list item and would add a class called highlighted to it.

Now lets see this

$(".item3").prev(".other").addClass("highlighted");

The above code would select the previous element and then check if it has a class called other. If not, as it in in our case, it will return an empty jQuery object(note that an empty jQuery object is not a null object. Its just like an empty array). The addClass function is called on the empty array and hence has no effect.

Now lets take a look at the prevAll() function

$(".item3").prevAll().addClass("highlighted");

This function, when called without the arguments will select all the previous siblings of the current element. In our case, all list items except list item with clas .item3 will be selected.

When passed an argument, only those previous siblings are returned that satisfy the test criteria.

$(".item3").prevAll(".item1").addClass("other");

In this case, only the previous siblings that have the class as 'other' will be returned by the selector.

Sometimes you have a requirement of selecting the first previous sibling that matches your selection criteria. For example in the below DOM structure, i have 2 list items with a class called 'other'. Suppose that i am traversing from list item 'item3' and i need to get the item having the html value of 'a'.i.e. the second list item.

  • 0
  • a
  • b
  • c

Here is how it can be done

$(".item3").prevAll(".other").eq(0).addClass("highlighted");

As you see, the prevAll function will traverse in upwards in the DOM for all the siblings. Since you need the first match, you select the element 0 of the matched set and apply your style class to it.


Another very useful function is the prevUntil() function. this function is used to select all the DOM siblings, before the current element, until an element is found that satisfies the search criteria.


$(".item3").prevUntil(".other").addClass("highlighted");

So, in our example, all the previous list items of class 'item3' will be selected until a list item with class 'other' is found on the DOM. This function, when called without the selector argument, works the same way as the prevAll function. So, it would be pointless to call this function without the selector argument.

The other functions - next(), nextAll() and nextUntil() work in exactly the same way as their counterpart function, apart from the fact that instead of selecting the previous siblings, these functions work on the siblings that follow the currently selected element.

These six functions make traversing in a given sibling structure pretty easy.

Happy Programming :)
Signing Off
Ryan

Friday, November 5, 2010

Finding elements using jQuery - Part 2

Today in this post, I am going to pick up from where i left off in the previous post where I discussed about how to use contexts and the usage of the find function and the children function.

Now, lets take a look at another cool way in which a jQuery allows us to traverse the DOM.

One of my favorite functions is the siblings function. This function, as the name suggests allows you to get the siblings of a the current element. For example, suppose you have a unordered list and you need to change the css of a particular list item on mouse hover to indicate that it is being highlighted, but at the same time, you will also need to clear the other list items that were previously hovered over. As is common in jQuery, there is more than one way to achieve this. Lets check out two different ways in which this can be done.

  • a
  • b
  • c


In order to achieve the effect that we desire, we can simply make use of the hover function.

$(".level1>li").hover(
     function(){$(this).addClass("highlighted")},
     function(){$(this).removeClass("highlighted")}
    );

But lets make things a bit more complicated. Suppose instead of simply highlighting the current li, your currently highlighted elements also need to print the information of the previously highlighted element. In this case, the hover function wont suffice. I know example sound a bit silly, but its a silly silly world out there, and requirements can be bizarre and unpredictable. In the next snippet, i am just going to demonstrate how the siblings function can come to the rescue when we need to countenance such requirements.

I am just going to print the value of the previously selected item on the firefox console(ah, yes I am a firefox fan, if you haven't already noticed that by now, although I occasionally use chrome as well for my adventures). Note that I will be printing it when my mouse pointer is over the new element, instead of when the mouse is coming out of the previous element.

$(".level1>li").mouseover(
     function(){
      var prevHovered = $(this).siblings(".highlighted");
      if(prevHovered.length!=0){
       console.log("prev html : "+prevHovered.html());
       prevHovered.removeClass("highlighted");
      }
      $(this).addClass("highlighted");
     }
    );


As you see in the above code, I use the mouseover function to handle the selection of the element. The siblings function will select all the siblings of the ul, but the important thing to note here is that the current element is not returned in the selected set. So, all you have is a set of siblings of the current element. You can narrow down the search by providing an optional selector to the siblings function so that only those siblings that match the selected criteria will be returned in the set. However, if you don't pass any argument, all the siblings will be returned.

All the above code did was to select the previously selected element, check if it was not null. It its not, print the html of that element on the console and remove the highlighting from that element.

Easy stuff.

But I mentioned before that I used the mouseover function instead of the hover function. The hover function can take either 1 or 2 arguments as callbacks that can be used to call your function. If only one argument is sent, it will called on both of the mouseover and mouseout event. If you provide two functions as arguments, the first will be used for a mouseover and the second will be used for the mouseout event.

I figured, instead of having an empty mouseout, i'd rather use the mouseover function since it is more natural to our requirement in this case. However you can replace the mouseover function with the single argument hover function in the above code, and it would still work the same.


There's more from where that came from. Stay tuned!


Happy Programming :)
Signing Off
Ryan

Struts 2 : Creating and accessing maps.

Today, in this post, I am going to discuss how to create and access HashMaps in Struts 2.

My environment has the following jar files.
struts2-core-2.1.8.1.jar
ognl-2.7.3.jar

Struts 2 makes extensive use of OGNL in order to retrieve the values of elements. OGNL stands for Object Graph Navigation Language. As the name suggests, OGNL is used to navigate an object graph. In this post, i am going to use the OGNL syntax to create Map on a jsp page, and show you how to iterate over it to fetch the keys and values from the map.

In the following example, i will create a map, on they fly in the iterator tag, and will use it in the body of the iterator tag.







Note the syntax that has been used to create a Map on a jsp page in struts 2 using OGNL. Once the map is created, the iterator tag can be used to iterate over each element of the map.

Now suppose the map that we want to access is in a map inside the HttpRequest. Assume that some action somewhere in the chain has kept a map in the request using the key "myMap". In order to iterate over the elements of the map, we can do the following







Okey now, enough with iterating over maps. I don't think there are any more permutations for accessing maps. But if i do find more, ill document them down here.

Consider a case where you dont want to iterate over the entire map. Instead, all that you want to do is to extract a value form the map based upon a key that is already known to you in your jsp page.

Assume that you have a variable in page scope called "runtimeKey" that you set using the s:set tag. The value of this variable is a string key that can be used to get a value from a map.

Here is how you can fetch the value from the map without iterating over it.




As you see, since the variable "runtimeKey" is an OGNL variable and is available on the value stack, it can be referenced using the # notations. Also not that instead of using the dot notation, I have used square brackets to fetch the key. This is because the value of my expression "#runtimeKey will only be evaluated when its inside the brackets. Also note that the value of the key runtimeKey is contained within single quotes to direct OGNL to evaluate it as a string when setting as the value for my key.


Consider another situation where your keys follow a pattern. For example key_1, key_2. And you have the values 1 and 2 as page scoped variables. So, now instead of having the string value of the key directly, you may have to construct the key using concatenation.



Your key pattern was set above. And you Map has a key called key_1. So, here is how you would have to concatenate your strings in order to construct the key and fetch the value.



Huh. So easy!

Thats all for now folks.. Stay tuned for more!

Happy Programming :)
Signing Off
Ryan

Thursday, November 4, 2010

Finding elements using jQuery - Part 1


Today in this blog post I am going to discuss a few ways in which we can find DOM elements using jQuery.

We all use jQuery selectors in order to select elements to work upon. Most of our selectors are usually based upon the id or the class or some other attribute, and sometimes even the structure of the elements being selected. However, apart from these selectors, jQuery also allows you to select elements in a completely different way, like all the siblings of an element, all the children of an element. It also allows you to search within the context of another element.

Lets see what I mean by that. Consider the following DOM structure.

  • a
  • b
  • c
    • c1
    • c2

As seen in the structure, i have one main ul which has three li elements. this ul acts as the main container. The third li element in the main container in turn has another ul which has three li subelements.

For both the ul elements, the li elements have been assigned classes pertaining to their location in the list. So, we ended up with a total of four li elements having the same class for the li element- item1 and item2.

Now let us see the various ways in which we can select the different elements in this structure.

As usual, we will be writing all our code in the jQuery onload function which is as follows.

$(function(){
//All our code goes here. });

Lets assume that we want to color all the elements that have the class 'item2' within our ul that has a class 'container'

There are actually three ways to achieve this.
Here is the first.

$(".container .item2").css({"background-color":"blue"});

This way is simple, and we use normal css selectors to find all the sub elements in the DOM under our .container that have a class named as .item2. This, in our case,would set the background color of both the li elements that have the 'item2' class.

Now lets see a second way to do it.

$(".item2",".container").css({"background-color":"blue"});

This is also equivalent tot the previous snippet. This selector makes use of "search context". A search context is nothing but the context in which the elements will be searched. So, if i were to read out the selector expression, it would be read something like this

'Select all the elements that have a class called item, that exist inside the element that has a class called container'

This means that the first argument that is passed to the selector is the actual search expression, whereas the second argument that we passed to the selector becomes the context of our search.

It also means that when we don't pass the second argument, the entire DOM structure is searched by default.

Here is the third way to do it.

$(".container").find(".item2").css({"background-color":"blue"});

In the above code, we are using the find() jQuery function to find the elements. If i were to read it aloud, it would be read as

'Select the elements with a class called container first, and inside all those selected containers, select the elements that have the class called item2.'

Sometimes, if your classes are unique, you may not feel the need to find elements using the context. Or, in many cases, it is possible to find the elements using a normal selector that would traverse the entire DOM. Why use contexts and confuse things?

However, when your structure becomes complicated, it may come in extremely handy to use contexts to find elements. Because, when you find using contexts, jQuery has to traverse fewer DOM elements to get the elements you desire to search, thereby saving you time and improving overall performance.

Sometimes, it it better to make use of a context when you already have a part of the search for the context already done for you.

For example, let us assume you register a click function for your container. And inside the click function, you need to do the same thing that we did above.

Here is how it could be done in the normal way

$(".container").click(function(){
$(".item2",".container").css({"background-color":"blue"});
});

But there is one thing to be noticed here. We are already in side the click handler of the container. That means, jQuery has already searched the DOM for our container. Then why do we need to again ask jQuery to search the DOM for the container? Instead, we can make use of the current context, and simply search for the item we want.

Here is how it can be done.

$(".container").click(function(){
$(".item2",$(this)).css({"background-color":"blue"});
});

The context in a click handler is determined by the value of the 'this' variable. So, finding elements can become easier for jQuery if you just know when and were you can reduce the lookups that jQuery has to do, by making use of an existing context.

That's all for now. I shall discuss more ways of finding elements using jQuery in future posts.
Till then, cya!

Happy Programming :)
Signing Off
Ryan

Wednesday, November 3, 2010

jQuery : Creating a custom widget


Today, in this post, I am going to discuss how to create a custom widget using jQuery.

Lets begin with the definition of a widget.

A widget in jQuery means nothing but a function that can be called on a jQuery selector that modifies the behaviour of all the selected elements by attaching data to the selected elements and maintaining individual state for each of these elements.

The important point to be noted here is the "state keeping" that is associated with each selected element. This is what makes the difference between a jQuery plugin and a jQuery widget. A widget can be considered to be an advanced form of a plugin.

Widgets can be of several types. For example, you may create a widget that simply formats the data in an element. Or you may create a widget that is closely associated to the structure of a html snippet, because it uses the html structure to create its layout. for e.g the "tabs" widget.

In this post, I am going to create a very basic widget, that actually does nothing useful. My objective here is to write a basic skeleton structure to create a widget that you can replace anytime with your own functionality.

Our prerequisites :

Download the jQuery UI plugin. This plugin contains the javascript files that are necessary to create a widget. Thats because the widget function is available to us via the UI plugin. Of course that does not mean that you can only create UI related widgets using this plugin. You are always only limited by your imagination.
You can download it from here. For the examples in this post, all you need is the four components that fall under the "UI Core" category. We will only be dealing with the basic stuff here. Come back when you are done.

Okey, now that you're back, I want to ensure two things before we begin.
  1. You have extracted the zip file in some arbitrary location on your disc. lets call it "jQueryUI". This folder should contain the "js" folder and the "development-bundle" folder. We shall be using he "jQueryUI" as the root directory where we would be creating our html page in which we would be using jQuery.
  2. You create a page called widgetExperiment.html in your root directory.


In the head section of your html page, include the following lines of code.


  
  
  
  


These are the scripts that we need to refer to in order to create our custom widget. As you can see, the version numbers of your script files may differ based upon when you are actually reading this blog. Just go to the appropriate directories and replace the src file names in the script tag with the proper file names.

Now, we are all set to crate our first jQuery widget.

Lets start with the standard "onload" function in jQuery.

$(function(){
//All our Code goes here
});

When creating a widget, the first thing that we need to do is to create an object that represents the functions and the data of our widget. This object acts as a prototype for our widget data. The purpose of this object is to encapsulate the functions and the properties that will be associated with each selected element returned by the jQuery selector expression.



var myPrototype={
      options:{level:1},
      setLevel:function(level){this.options.level=level;},
      getLevel: function () { return this.options.level; },
      _init: function() { this.setLevel(this.getLevel());}
     };

As can be seen above, I named my prototype object "myPrototype". Inside my prototype, i have a few functions and an object called "options".

There are two things that you need to know about the properties that are created inside a widget.
The function names that begin with an underscore are private. i.e. these functions cannot be called from outside of the widget.

All the data, pertaining to the state of the widget should be kept in an internal object called "options".
An instance of the widget is created for each element returned by the selector. The options object ensures that for each instance of the widget that is created, the properties remain private to that particular instance.

Initialization of your widget if required, must take place in the _init function. You can also create a destroy function to perform any cleanup when your widget instance is destroyed. These functions are called automatically and are part of your widget lifecycle.

As seen in the code, for my widget, i created a private property called "level" and two "getter/setter" functions to manipulate this property. The getter/setter functions are public by virtue of not starting with an underscore.

Calling these functions are not done in the usual manner. We shall see how to invoke these public functions once we have created the widget.

Creating a widget is very simple. All that you need to do is to associate your prototype object with a name and pass it to the jQuery widget function. Here is how it is done

$.widget("ui.myWidget",myPrototype);


The jQuery widget plugin function is used to create your widget by assigning it a name in the namespace "ui.myWidget" and then passing the object that we use as the prototype object in the second parameter.
Although the namespacing is "ui.myWidget", your widget is simply named myWidget and that is what your plugin function will be called.

Associating your widget with an element is a complete no brainer. For example, the following code associates all my divs on the page with my widget. (you dont want to associate all your divs with a widget unless ur a total nut, or if you are testing something like the way I am doing now)

$("div").myWidget();

Now lets see how to use our newly created widget. If you remember, when creating the widget, we declared a property called "level" that set to an initial value of 1 in the widget. Now we are going to write a simple click handler for our divs that sets the value of the level and prints it on the console.

$("div").click(function(){
      
      $(this).myWidget("setLevel",4);
      
      console.log($(this).myWidget("getLevel"));
      
     });



In the following example, notice how we called the public functions getLevel and setLevel. Also notice how we passed a parameter to the setLevel function of our widget. The first argument is treated as the function name and the second argument onwards are treated as the arguments for the function being invoked.

Here is the entire code in a single snippet


var myPrototype={
      options:{level:1},
      setLevel:function(level){this.options.level=level;},
      getLevel: function () { return this.options.level; },
      _init: function() { this.setLevel(this.getLevel());}
     };
     
     
     $.widget("ui.myPrototype",myPrototype);
     
     
     $("div").myPrototype();
     
     $("div").click(function(){
      
      $(this).myPrototype("setLevel",4);
      
      console.log($(this).myPrototype("getLevel"));
      
     });


Well, that seemed pretty easy, didn't it? But our widget lacks one important thing that we would need to do in most of our widgets. That is, to access the current element to which the widget is attached, inside the widget. You cannot use "this", because inside the object, the keyword "this" represents an instance of the widget. The actual element associated with the object is accessed via "this.element", which is a jQuery object representing the dom element.

So, if you were inside the init method and you wanted to print the value of the id of your selected element, that could easily done by the writing the following lines in the init method

console.log("inside init : "+this.element.attr("id"));

So, thats one more thing settled.

Lets add a little more 'dummy' functionality to our code by allowing it to interact with the mouse. In order to allow your widgets to interact with the mouse, you need to create your widgets in a slightly different way.

Here is how you created the widget in the normal case ;

$.widget("ui.myWidget",myPrototype);

And here is how you will create it when you need mouse interaction

$.widget("ui.myWidget",  $.ui.mouse,myPrototype);

Once you have done that, you can need to override a few functions to handle mouse related events on your widget. But before that you should call the _mouseInit and _mouseDestroy methods in the _init and destroy methods of your widget respectively.

Here is the code in all its mighty form!

var myPrototype={
      options:{level:1},
      setLevel:function(level){this.options.level=level;},
      getLevel: function () { return this.options.level; },
      _init: function() { this._mouseInit();},
      
      
      destroy: function() {
       this._mouseDestroy();
       return this;
      },
      
      _mouseCapture: function(event) {
       console.log("inside capture: x("+event.pageX +") y("+event.pageY+")" );
       return true;
      },
      
      _mouseStart: function(event) {
       console.log("inside start: x("+event.pageX +") y("+event.pageY+")" );
       return true;
      },
      
      _mouseDrag: function(event) {
       console.log("inside drag: x("+event.pageX +") y("+event.pageY+")" );
       return false;
      },
      
      _mouseStop: function(event) {
       console.log("inside stop: x("+event.pageX +") y("+event.pageY+")" );
       return false;
      }
      
     };
     
     
     $.widget("ui.myWidget",  $.ui.mouse,myPrototype);

I hope this bare bones example comes in handy to get you started quickly on creating simple widgets.

Thats all for now folks!

Happy Programming :)
Signing Off
Ryan

Saturday, October 30, 2010

Javascript prototype property

Today, in this post, I am going to discuss about the prototype property of classes in javascript. I came across this property when i was trying to learn about classes in javascript. Javascript, being a dynamic language, allows you to have a number of bizarre yet interesting features that you don't find in mainstream languages. the prototype property is one such feature. Due to its idiosyncrasy, it is usually a source of confusion. I am just going to brush on the basics here so that it becomes easy for us to spot loopholes in the more complex code that we usually write.

Here are our objectives.

  1. Learn where and why the prototype property is usually declared in javascript.
  2. Learn how to use the prototype property in javascrpt.


First, lets try to explain why the prototype property is used in javascript.
The prototype property comes in handy when you have a class and you have already created a set of objects and at a certain point of time, you want to introduce a new property in each of your objects.

Lets see with an example. First we create a class called Person with a property called name

function Person(name){
      this.name = name;
      this.getName=function(){return this.name;};
      
      this.setName=function(nameArg){
       this.name=nameArg;
      };
     }

Then we create a few objects of this class as follows.


var p1= new Person("person1");
var p2= new Person("person2");


Now suppose that need to add a property called 'age' for all the person objects that are currently created. The first way that might come to our mind is to modify the class declaration and add a new property called age to it in the same way that we added name property. But what if the class Person is declared in some common file and is referenced by different scripts, and my requirement necessitates that the new property should be available only for the currently executing script. This is where the prototype property comes to the rescue.

We can add a property to all the instances of the class by writing the following lines of code.

var p1= new Person("person1");
     var p2= new Person("person2");
     
     Person.prototype.age=30;
     
     console.log(p1.age);
     console.log(p2.age);


As seen in the above code, when i print the value of the variable age, both the objects are able to print the new property.

An interesting thing to not here is that the property called age that has been newly created here is actually a class variable. i.e. all the objects created are able to see the same value of the newly added property. What this means is that if we try to modify the property via one variable, all the objects will see the new value of the property. Since objects are equivalent to functions in javascript, the prototype property can be used to create new functions on the class as well.

Lets modify the code for the Person class by adding a function to set the age.

this.setAge=function(argAge){
       Person.prototype.age=argAge;
      }

So far so good.

Now, lets see what happends when we print the age of the objects after modifying the age for one of the objects.

Person.prototype.age=30;
     Person.prototype.setAge=function(argAge){
       Person.prototype.age=argAge;
     }
     
     
     console.log(p1.age);
     console.log(p2.age);
     
     p1.setAge(40);
     
     console.log(p1.age);
     console.log(p2.age);


If you run this, you would see that both the objects p1 and p2 have the same value of age after being modified. So, after all, what was the use of creating a new property if it is being shared across all the objects. Also, we saw that in the setAge function that we are using the fully qualified syntax to access the age property. Lets see what happens if we use the shorthand notation in the setAge method.

Person.prototype.setAge=function(argAge){
       this.age=argAge;
     }

     console.log(p1.age);
     console.log(p2.age);
     
     p1.setAge(40);
     
     console.log(p1.age);
     console.log(p2.age);

Now, if you were to print the age of the two objects, they would differ. Seems like our problem is solved. But what actually was the cause of the problem in the first place? The problem arises due to the way in which the javascript engine searches for the age property on the object.

When trying to access the age property, the engine will first search the property on the instance of object. i.e. this.age. If this property is not available on the object then the engine will search for the property in the prototype property. Since the variable 'age' is declared on the prototype, it is found and printed on the console when we try to print it for the first time.

But when we set the property using the setter method using the "this.age=argAge", a new property is created on the current instance and its value will be set to the value passed as the argument.

You might be wondering, what is the use of creating a property using the prototype method. The main advantage that you get by using the prototype property is that you can create new class level properties or functions at runtime without modifying the class. And from then on you can read the value of this property from all the instantiated objects. You can then also create a property of the same name on the objects using the value of the prototype property.

For example

Person.prototype.addAge=function(){
      this.age=this.age+1;
     }

p2.addAge();
     
     console.log(p2.age);


In the function addAge, the "this.age" on the RHS will refer to the Person.prototype.age the first time it is called and the "this.age" on the LHS will create a new public property called "age" on the current instance. Further invocation on the method will cause the newly created publicly created property.

Thats all for now folks!

Happy Programming :)
Signing Off
Ryan

Javascript classes

In this post, i am going to discuss how to create classes in javascript and how classes in javascript behave differently as compared to classes in other languages like Java.

Here are our objectives.

  1. Learn how to create javascript classes.
  2. Learn how to create properties in javascript classes.
  3. Accessing the properties of javascript classes.


Lets walk through them one by one.

In javascript, classes are created by merely creating a constructor function of the class. The functions declared within the constructor on the 'this' object become the "public" functions of the class. The variables declared within the function on the "this" object become the "public" variables of the class.

Lets see with an example of a class called person.

function Person(name){
      this.name = name;
      this.getName=function(){return this.name;};
      
      this.setName=function(nameArg){
       console.log(nameArg);
       this.name=nameArg;
      };
     }

As seen above, i created a function named Person. Then i created a property called name on the "this" object. And i also created a bean style getter and setter for this property on the "this" object. Here is how we instantiate the class.

var p1= new Person("ryan");

As you see, instantiation is pretty simple and quite similar to your conventional languages like Java.

Now lets see how to invoke the methods and access the properties.

console.log(p1.name);
     
console.log(p1.getName());
     
p1.setName("public name");
     
console.log(p1.getName());


Note that the property "name" is a public property, because it is declared on the this variable. So, it can be accessed without any getters and setters. I have simply introduced getters and setters for the "name" property to demonstrate how private properties differ from public properties, which i will be covering in the next example.

So far, so good.

Now lets see how the code for the person class would change if i were to make the "name" property private.

function Person(){
      var name;
      this.getName=function(){return name;};
      this.setName=function(nameArg){       
       name=nameArg;
      };
     }


Okey, lets make a note of the differences. First thing you see is that i created a property called "name" using the var keyword. Now it is a private variable. The point here is that all the variables declared in side a class, that are not declared on the this variable are private variables. And the public getter/setter functions, are allowed to set and get the private variable directly without any using the "this" keyword. This is possible due to javascript closures. Closures allow you to access locally declared variables from with locally declared methods. And the scope of the local variable lasts as long as the scope of functions where it is being used.

As i said before, if all local variables are private variables, then the following class declaration should be equivalent to the previous one for declaring private properties.

function Person(name){
      this.getName=function(){return name;};
      this.setName=function(nameArg){
       console.log(nameArg);
       name=nameArg;
      };
     }

And guess what, they are equivalent. Thats because, the variable passed as an argument in a constructor is a local variable in the function, just as in Java. Hence, it automatically becomes a private variable.

Here's how it can be accessed

console.log(p1.getName());
     
     p1.setName("surprise");
     
     console.log(p1.getName());

Pretty simple.

However, it is better not to have private variables and corresponding getter and setter methods for them because for each object that you create, a new copy of the methods would be created for each object, and hence it would have significant memory overload if you intend to create several objects. Its always better to create public properties and mainly use function pointers instead of functions in your classes. Ill be discussing about these topics in my upcoming posts.

Till then.
Hasta La Vista!

Happy Programming :)
Signing Off
Ryan

Monday, October 18, 2010

Struts 2 - Creating Dynamic results

Hi everyone,

Today, in this blog post, I am going to jot down a way to create dynamic results in struts 2.

Lets first begin with a few questions.

What do i mean by dynamic results?


We all know that struts allows us to configure the pages to which request must be dispatched to redirected to, via the "result" tag. However, at times, it may be hard to determine at configuration time itself, which pages need to be set as the result. For example, your business logic may determine the action or the jsp that you need to forward to. In the following example, I am going to try and allow the dynamic results in Struts 2.


Whats my objective?


To create an action class that determines the jsp page name that we need to forward to based upon some business logic.
Configure the action in my struts configuration file(struts.xml) for dynamic results
Invoke the action.


Now, lets begin.

Firstly, we create an action class called DummyAction2. (STATUTORY WARNING : The naming conventions in this post, and for the record, many others, might sound bit weird, but i have a tonne of experiments, and its really hard to settle on a proper name for every whim that comes to my mind. So, please bear with me on that note. :> )

My action class is like any other action class. It contains an execute method. But in my case, the execute method does not do anything, except return a "success" string. Thats because i have another business method, which i am going to name as(surprise! surprise!) anotherMethod. This is the method that i am going to invoke using my action mapping.

In order to be able to identify the page that we need to display, we need to create an instance variable that holds the name of the page that we need to forward to. And we create getter/setter methods for this instance variable.
Ill just keep the business logic simple, and store the name of the next page to be displayed, in this instance variable when the action is invoked.

Lets take a sneak peek at the code in the action class.


public class DummyAction2 extends ActionSupport{

    private String nextPage;

    public String execute()
    {
        return ActionSupport.SUCCESS;
    }

    public String anotherMethod(){
        String actionStatus=ActionSupport.INPUT;
        System.out.println("Another Method in Dummy Action");
        
        nextPage = "myPage.jsp";

        actionStatus=ActionSupport.SUCCESS;
        return actionStatus;

    }
    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return nextPage;
    }

    /**
     * @param nextPage the nextPage to set
     */
    public void setNextPage(String nextPage) {
        this.nextPage = nextPage;
    }
}

As you see, there's nothing much going on in my anotherMethod. All i do is to set the value of the next page in the instance variable. And then i simply return a success response from the action class.

The mapping is where the real magic takes place. In your mappings, you can dynamically determine the value of a variable in an action using ordinary EL. Lets see the code first.


                ${nextPage}
            

Okey, i was lying. Its no magic. Its just that, in your struts configuration file, you can access the properties in your current action class using ordinary EL. Thats exactly what we have done here. The string ${nextPage} is used to extract the value of the property named "nextPage" from the current action. And since that action is a jsp page in our case, that's the page that will be rendered to the user.

Invoking the action is done in the same old fashioned way.

Invoke Dynamic Result

I guess, the idea is pretty clear.

Thats all for now. See you folks next time!

Happy Programming :)
Signing Off
Ryan

Monday, September 13, 2010

A sample paint application using jQuery

In today's post, I am going show how one can associate mouse events to an html element using jQuery. JQuery allows us to bind a large number of events to objects fetched by using a jQuery selector.

The following is the list of events that are recognized by jQuery :
blur, focus, focusin, focusout, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error.

Binding events to jQuery usually means making the selected Dom Object aware of the event and take necessary actions based upon it.

The primary function that jQuery uses to perform these binding is called (surprisingly!) the bind() function.

The syntax of the bind function is simple. For a given selected set of jQuery object, you indicate the function that needs to be called when a particular event takes place on that DOM object.

So, basically, its an eventname - handler function() duo. Occasionally, you may also need to pass additional parameters to the handler function. That is done by passing a map of the parameters in the arguments of the bind function.

Following is the basic syntax of the function.

.bind( eventType, [ eventData ], handler(eventObject) )


However, for most tasks, you would be using the following version of the function

.bind( eventType, handler(eventObject) )

In this post, I am going to create a simple application that acts like a very very primitive version of MS Paint. Here's the basic idea : -

I am going to create a div, that will act as a canvas. Using the mouse, the user should be able to draw curves on the screen as he drags the mouse on the canvas, just like the way we do using pencil and paper. The only difference is that instead of the pen, you use the mouse, and instead of the paper, you have a div(to which I will assign appropriate dimensions) on which to draw.
To make things a bit more interesting, (just a bit more), i will allow the user to choose a color for the paintbrush.

The body of my html page has 2 parts- the canvas, and the color palette.

green
blue
red
black


The div that I am going to use as a canvas has been given an id if "canvas".
The palette contains four div's that act as buttons that can be used to select the color. The content of the 4 div's is nothing but the name of the color the div represents.

So, here's the basic plan to achieve what i want to do : -
  1. Track the movement of the mouse, the moment it is pressed, and stop tracking it the moment it is released. This will be achieved by binding appropriate handlers to the mousedown event, the mousemove event and the mouseup event.
  2. When the mouse is being dragged on the canvas, i need to create a dot at the position of the mouse. In this example, i am going to create a 4 pixel dot. This dot is nothing but an span element having absolute positioning. A new span will be created for every position that my mouse cursor moves over in the area described in my canvas.


Here is the basic CSS that I will be using to achieve the desired layout.

.canvasStyle{
 width:500px;
 height:500px;
 background-color:#cfcfcf;
 float:left;
}

.dots{
 width:4px;
 height:4px;
 position:absolute;
}


.palleteStyle{
 float:left;
 padding:10px;
 position:relative;
 text-align:center;
}

.colorChooser{
 border:solid 1px #000000;
 -moz-border-radius: 8px;
 -webkit-border-radius: 8px;
 border-radius: 8px;
 margin:5px;
 padding-bottom:8px;
 width:100px;
 height:12px;
}


The css is pretty simple. I have a class 'canvasStyle' to define the layout of my canvas. Then I have a class 'dots' to define the layout of my dots. Then a class 'palleteStyle' to define the layout of my color palette. And then a class 'colorChooser'.

Now lets talk about the javascript. All my code is in the jQuery onload function. Since this is the only functionality of my sample web page, I have taken the liberty to use global variables within this function. You may have to use a more structured approach if you want such functionality to coexist with your existing code. (making a widget would be a good idea, but we shall see about that later)

The only global variable that i am going to use here is the color of the brush. Initially, I set it to black. Here is the code for it.


$(function(){
 var bkcolor="black"; 
});

Now, the first thing i need to do is to bind the mousedown and mouseup event of the canvas to a particular function in which i will do my additional tasks.

Fortunately, the code for binding mouse events in jQuery is simpler than you can even imagine.

$("#canvas").bind('mousedown',function(event){
 
});


$("#canvas").bind('mouseup',function(){
 
});

The next thing that i need to do is to enable the user to click on any of the four div's on my color palette and be able to set the color variable based upon his selection. Since the color is the same as the inner html of the div's the code to set the color of the brush is pretty trivial. (dont look at me like that, i did this to make my life a bit easier!)

$(".palleteStyle").click(function(event){
 $target=$(event.target);
 bkcolor=$target.html();
});

In the above code, as you can see, instead of binding a separate function to each of my coloring div's, i chose to bind the click event handler to the parent container, i.e. my color palette. Inside the event handler, I determine the target of the click by using the 'target' property of the event object that jQuery allows me to pass to my event handling function. Once I get hold of my target, all I need to do is to set the value of the global variable to the html of the selected div.

Well, now there are only 2 important things remaining. Binding and unbinding the mousemove event on mouseup and mousedown. The other thing is to add a span to my canvas at the position of the mouse cursor.

First things first. Lets see the code for binding and unbinding the mousemove events.

$("#canvas").bind('mousedown',function(event){
 $(this).bind('mousemove',function(event){
         //some code goes here
 });
});


$("#canvas").bind('mouseup',function(){
 $(this).unbind('mousemove');
});


Well, quite simple eh? Ok then, lets move on to the next task of adding a span.

For adding a span, we first need to identify the position of the mouse cursor. This task will be handled in the mousemove handler function. As you can see above, the handler function takes and event variable as an argument. This variable can be used to identify the x and y coordinates of the mouse as and when it moves.
the X and y coordinates of the mouse can be retrieved from the pageX and pageY attributes of the event object. After that, all we need to do is to add the span to the dom inside the canvas. We achieve that by using the append() function. That said, the following code should be easily understandable.

$("#canvas").bind('mousedown',function(event){
 $(this).bind('mousemove',function(event){
  var dot ="";
  $(this).append(dot);
 });
});

The above code simply creates a span and sets the left and right css attributes to the pageX and pageY. And of course I set the background color to the bkcolor global variable.


Now, just to add a little more spice, ill change the visual appearance of the color selection div's based upon the color the represent. Here's the code for it.

$(".colorChooser").each(function(){
 $this = $(this);
 var bkcolor=$this.html();
 $this.css({"background-color":bkcolor,"color":"white","opacity":"0.8"});
});

Ya, I know, I unnecessarily made it fancy, but believe, you got my point.

Time to see the entire javascript for this example in one huge chunk. So, here goes nothing : -

$(function(){
 var bkcolor="black";
 $("#canvas").bind('mousedown',function(event){
  $(this).bind('mousemove',function(event){
   var dot ="";
   $(this).append(dot);
  });
 });
    
 
 $("#canvas").bind('mouseup',function(){
  $(this).unbind('mousemove');
 });
 
 $(".colorChooser").each(function(){
  $this = $(this);
  var bkcolor=$this.html();
  $this.css({"background-color":bkcolor,"color":"white","opacity":"0.8"});
 });
 
 $(".palleteStyle").click(function(event){
  $target=$(event.target);
  bkcolor=$target.html();
 });
});

Thats pretty much it takes to make something as simple as a bare bones paint application.
Here is the screenshot of how it looks in Chrome on my pc.



Forgive me, my calligraphy with the mouse ain't so good. But its kinda fun, especially if it can be done in a browser! And of course, jQuery makes it unbelievably easy :)

Cheers!
Happy Programming :)
Signing Off
Ryan

Saturday, August 28, 2010

A first look at creating custom jQuery plugins

In my previous posts, we saw several ways to manipulate functions and how functions and objects can be used almost interchangeably in javascript. In this post, I am going to use a popular javascript framework jQuery to create a custom plugin. If you are new to jQuery or any other javascript frameworks, then i suppose this post is definitely not for u.

However, for those who have been fortunate enough to have had the time and patience to work with jQuery, this post should be like a piece of cake.

So, what are jQuery plugins?
In short, jQuery plugins are functions that can operate on a wrapped set of jQuery objects.

For example, consider the usage of the click() function. This function is used to attach a click event handler to a wrapped set of jQuery objects, The objects in turn are obtained using jQuery selectors.

In this post, I am going to try and create a small plugin that contains some custom css and a few event handlers. The code is trivial, and one does not require to create plugins for such requirements, but for a  demonstration purpose, this should suffice.

So, here's the idea
I want to create a div that i am going to call the "main div" that has three child div's. The first child is a header div, the second child is a content div and the third child is a footer div. When the user clicks anywhere on the main div, the string "You clicked + div id" should be appended to the html that is part of the the content div. To add a bit more spice, i also want the content in the Header and Footer to be white in color.

This plugin allows to apply this effect to any html element that has the same structure as the above div's, i.e. one parent container with three children.

Lets see the html first.

Heading
div 1 content - custom enclosing plugin
footer1

Lets first clearly identify that major tasks that demand our attention.

  1. Color the text content of the header and footer div's
  2. Add a click event handler to the "main div", that communicates with the "content div" which happens to be my second child element in the structure shown above.


Lets name our plugin encloseme().

But first we need to get hold of our main div. Right? So, in this experiment, I am going to use a jQuery selector to select a div that contains the string "main". And then I am going to apply my plugin to it like this :

$("div[id*=main]").encloseme();

The above line would select all the div's whose id's contain the text "main", and apply the plugin encloseme() to it.

Now, before I begin writing the code for the plugin, I am going to use a feature of javascript that that i wrote about in my previous posts - the way of calling a function anonymously.

In order to use the "$" symbol in a non conflicting way, I am going to pass the jQuery object as a parameter to the anonymous function that will in turn create my plugin.

Here is the snippet.

(function($){
 //plugin code goes inside here.
        //Here, the "$" symbol can be used without bothering about any sort of 
        //conflicts with external code(i.e. code outside the body of this function).
})(jQuery);

Creating a plugin requires you to create a function on the jQuery.fn object.
The jQuery.fn object is equivalent to the prototype object in javascript that is used to add more functions.

Lets see the code to create our plugin.
$.fn.encloseme=function(){
return $(this).each(function(index,element){
  
  //plugin code for each selected element in the matched set goes here.
  
 });
};

There are two things that you need to notice in the above snippet.
The anonymous function is terminated by a semicolon, unlike other functions that you create in jQuery.
The function returns the result of iterating each element in the matched set. i.e. the function returns a jQuery object that represents a matched set.

Although we can choose to return anything, but the basic idea here is that your plugin should blend in seamlessly with other jQuery functions, and for that to happen, you must ensure that your plugin allows method chaining. It is considered a good practice to return a matched set from your plugins if you don't want to surprise your web authors. If you want to surprise them, well, then you better buy yourself an Iron Man suit, because sooner or later, you are certainly going to need the protection it offers!


Adding colors to the child div's is a pretty trivial task. Ive also added a bit more css to add border to the main elements. Lets see the code for it.

$.fn.encloseme=function(){
  return $(this).each(function(index,element){
   
   $(this).css({
      "background-color":"grey",
      "border-style":"solid",
      "border-width":"2px",
      "width":"200px"});
  });
 };

In the above code, i am selecting the container tag represented by $(this) and then adding a background color it and a few more styles.

Now lets handle the children!(OMG)
Don't worry, handling children in jQuery is not as tough as it is in Real life. The first thing that you need to do is to find a way to get the children of your container. jQuery allows you to do so by callinng the children() function on the container. This function returns a jQuery object that represents the immediate children of the selected container.

the following code can be used to color the text of the children to white.

$(this).children().css({"color":"white"});


Before delving further in this example, I must remind you of the fact that my example is assuming that my container contains 3 child elements and that i am trying to achieve the effect of appending some random text to the text of my second child element whenever the user clicks anywhere on the parent container. That should explain the use of absolute indexing in lines of code that follow.

In the next snippet, i am going to override the css property : color, of the second child element and restore it to black.

$($(this).children()[1]).css({"color":"black"});


jQuery indexed are 0 based. So, the code $(this).children()[1] selects the second DOM element. Since I need to call a jQuery function on the selected DOM, enclose it inside another jQuery selector - $($(this).children()[1])


Now, the only task that remains is to add a click event handler to the main container and associate it with the html text of my second child element. The following code will do my job.


$(this).click(function(){
 $($(this).children()[1]).html($($(this).children()[1]).html() + " You clicked "+ $(this).attr("id"));
});


Following is the final code for the plugin :

(function($){
 $.fn.encloseme=function(){
  return $(this).each(function(index,element){
   
   $(this).css({
      "background-color":"grey",
      "border-style":"solid",
      "border-width":"2px",
      "width":"200px"});
      
   $(this).click(function(){
    $($(this).children()[1]).html($($(this).children()[1]).html() + " You clicked "+ $(this).attr("id"));
   });
   
   $(this).children().css({"color":"white"});
   $($(this).children()[1]).css({"color":"black"});
  });
 };
})(jQuery);



Applying my plugin to my container is pretty easy. Here's the code for it.

$("div[id*=main]").encloseme();


But I already told you that before, didn't I? Well, since its a plugin, it can practically be applied to any jQuery element. In our case, since we are manipulating the second child through absolute indexing, the plugin can be applied to any container which has at least 2 children.


For example, we can create a unordered list with three child elements and then apply the plugin to the unordered list.

Here's the html for it


  • item1
  • item2
  • item3


And here is the jQuery that can be used to apply my plugin

$("ul").encloseme();


That does it!

Though I must say that the above example is not highly usable for practical purposes(At least i personally haven't been able to apply this particular plugin anywhere), however it demonstrates a few things that plugins can be used for :

Grouping together functionality for several elements. Here we have grouped together the click and css aspects of a set of elements.

Adding new custom behavior to jQuery, although one must be careful while creating too many plugins as they may clutter the namespace.

We can also customize plugins by sending them arguments or options. But thats another long story, and ill spare you the details involved...at least for now!

Cheers!
Happy Programming :)
Signing Off
Ryan

Sunday, July 11, 2010

Javascript functions - Part 3

In this post, I am going to experiment with a few more ways of invoking functions in javascript. In my previous post Javascript functions - Part 2 I elaborated on a few ways in which functions can be called.

Unlike many other languages, javascript functions are more than just functions. They are objects as well. And since functions, being an object, can have more functions defined for them, javascript allows us to have two pretty useful functions that can be used to call functions.

Every function in javascript can be called by its name and passing parameters. However, the context in which a function is being called can be different everytime.

What? Context? Now where did that come into the picture?

Well, if i were to define the context, I'd say that its nothing but the value of the 'this' in the function that is being executed. Seems pretty simple eh?

But somehow, the value of 'this' is not as easily grasped while programming in javascript. This is because 'this' is not your usual 'this' that you see in other languages like Java. For someone like me who has been meddling with hard code oops concepts, the way in which 'this' was being used in the javascript was pretty elusive in the beginning.

I am not going to be talking much about 'this' in today's post, however, there is something that we need to know before we can check out the the 2 new ways in which functions can be invoked in javascript.

'this' is something that you must know! < insert wicked laughter here >

Whenever a function is being invoked in javascript, and there is no object who is the invoker of the function, the window object is considered to be the default invoker.
Also, when defining objects that are not members of other objects, the objects are considered to be members of the default object - the window object.

Well, the above two lines are pretty simple. But lets see how these simple little things can make the behavior of code unpredictable when programming if you are not careful with your code.

Lets assume we have the following function defined in our script

var v={a:10};
  v.fun4=function(){
   alert("fun4 "+ this);
   fun5();
  }

function fun5(){
   alert("fun5" + this);
  }

v.fun4();


What I have done here is pretty simple. I created an object 'v' with a property 'a' and a function fun4(). fun4() alerts a message and then calls fun5(). Run this code and see what happens. As you see, the first alert indicates that the value of the 'this' keyword in the function fun4 is the object(in our case it is 'v'. You can check it by printing the value of v.a). But the second alert indicates that the value of 'this' is not the object v, but instead it is the default window object.

If you are not familiar with javascript, you might be perplexed, maybe just for a while, before the concept actually begins to reveal itself.

As you see, during the declaration of the function fun5(), it is not declared as a function of any object. Hence, this function is implicitly a function of the window object. Functions declared on the window object are global and can be called by any other function, which is exactly what our fun4() does. Hence, the default context of the function fun5() is the window object, which is the value of our 'this' keyword.

But what if you want the value of 'this' to be the object 'v' in fun5? What do you do?
Well, if you are thinking that you can simply replace the line fun5() with this.fun5(), that, my friend, is simply not gonna work. That's because, the function fun5() is not a function of the 'this' object in fun4().


However, there is a way to do it. The call() and apply() functions in javascript can be used to aid us in exactly this sort of scenario. these functions are used to set the context of the function, which is thereby reflected in the value of the 'this' keyword of the function.

In the following piece of code, we are going to declare 2 more functions on our object 'v'. And 2 global functions on the window object.

v.fun6() invokes global function fun7() using the call() function.

v.fun8() invokes global function fun9() using the apply() function.

v.fun6=function(){
   alert("fun6 "+ this);
   fun7.call(this,'ryan');
  }
  
  function fun7(arg){
   alert("fun7" + this + " arg : "+ arg);
  }
  
  v.fun8=function(){
   alert("fun8 "+ this);
   fun9.apply(this,['ryan']);
  }
  
  function fun9(arg){
   alert("fun9" + this + " arg : "+ arg);
  }
  
  v.fun6();
  v.fun8();


As it can be seen, the global functions also receive a parameter. The syntax of call() and apply() are quite similar. The first argument of both these functions is used as the context in which the actual function is to be called.

The call() method can have many arguments after the first argument such that each argument becomes the argument to be passed to the actual function.

The second argument of the apply() function takes an array of values that are to be passed as arguments to the actual function.

Run the code and see for yourself, how the value of the 'this' keyword is now appropriately being used in the global functions.

One implication of this sort of technique is that you can have a number of global functions, each of which does a single common task. And you can have several objects, belonging to different classes that call these global function using their own context, thereby reducing the redundancy of existing functionality.

That's all for now. We shall do some more experiments in the next post. :>

Happy Programming :)
Signing Off
Ryan

Saturday, July 3, 2010

The Observer Pattern

In today's post, I am going to discuss about the observer pattern. This is one of the most widely used patterns in most J2EE applications. I say this because of the inherent simplicity of this pattern and the the fact that it is highly possible that you are already implementing this pattern without actually being aware of it! This is something that certainly cannot be said about other patterns like the Visitor or the Factory pattern.

As I always do, this time as well, i am going to elaborate the usage of this pattern in a fictional - game like situation.

Lets imagine we are playing a horror game. Yea, this time i pick a horror game instead of the good ol FPS!

First, lets begin with a somewhat formal introduction to the pattern.

As the name suggests, the Observer pattern is basically used to associate an object A with a group of other objects that observe any changes in the properties of the object A, and perform some very critical, earth shattering tasks, based upon the change made to the properties of the object A.

Well, its like another way of talking about the event - event listener, model of programming.

There are primarily three major concerns in the Observer pattern.
1) The object being observed - The Observable object.
2) The objects that observe the observable object - The Observer objects.
3) A way to associate and invoke the Observable object with the Observers - The Delegate function.

To be concise - Observer Objects Observe Observable Objects.
That's 5 O's in one sentence!

There two are styles of implementing the Observer pattern - The Push model and The Pull model. These two models differ in the way in which the Observers and the Delegate function are designed. The observable object remains the same. I will elaborate both of these models later in the post and also discuss the pros and cons of both the techniques.

However, now its time to play some game.

The protagonist of our horror game features a very bold player named ScoobyDoo.
So, we create a basic player class with three instance variables :
name, xCoordnate, yCoordinate. Here is the class definition.

public class Player {
    
    private String name;
    private Integer xCooridinate;
    private Integer yCooridinate;

    public Integer getxCooridinate() {
        return xCooridinate;
    }

    public Integer getyCooridinate() {
        return yCooridinate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void moveForward(Integer steps){
        xCooridinate+=steps;
    }

    public void moveBackward(Integer steps){
        xCooridinate-=steps;
    }

    public void jump(Integer height){
        yCooridinate+=height;
    }

    public void fallTo(Integer height){
        yCooridinate=height;
    }
}

I have also added a function that allows the player to move forward and jump(i.e. move upward) and vice versa. These will be used to manipulate the xCoordinate and yCoordinate properties of our our Player.

Now, I don't think a game can be made scary without proper lighting and sound effects. But what makes a game scary is the appropriate timing of these effects.

Lets assume a scene where ScoobyDoo enters an empty room. As of now, the lights are bright and shining. The xCoordinate and yCoordinate of the player are initialized to 0 when the player enters the room.

Now what we want is that when ScoobyDoo is right in the middle of the room, i.e. approximately 10 steps into the room, the lights should suddenly begin to flicker.


Not only that, but we also want a scary sound to start playing in case ScoobDoo tries to act smart and tries to jump up to run out of the room.

Yea, it might sound as if I am being so mean by trying to scare the shit out of this dog, but hey, i am not to blame. I bet this dog would get scared of the sound of his own fart as well!

Okey, back to work.

What we need is a way to observe the coordinates of ScoobyDoo in the room and take appropriate actions when his coordinates cross a certain threshold.

So, here, the Observable object is the Player.

Before we begin we need to define a few interfaces that will be used to generically use and handle Observers and Observables.

Lets see the definition of these interface first.

public interface Observable {
    public void notifyObservers();
    public void addObserver(Observer o);
    public void removeObserver(Observer o);
}


public interface Observer {
    public void update(Object o);
}


Lets create Observers.

public class SoundEffectController implements Observer{

    private boolean isSoundPlaying = false;

    public void playSound(){
        System.out.println("Play an eerie sound");
        isSoundPlaying = true;
    }

    public void update(Object o) {
        if(o instanceof Integer){
            Integer yCoordiante = (Integer)o;
            if(yCoordiante>0 && isSoundPlaying== false){
                playSound();
            }
        }
    }

}



public class LightEffectController  implements Observer{

    private boolean isLightFlickering = false;

    public void flickerLights(){
        System.out.println("Flicker the lights");
        isLightFlickering = true;
    }

    public void update(Object o) {
        if(o instanceof Integer){
            Integer xCoordiante = (Integer)o;
            if(xCoordiante>10 && isLightFlickering==false){
                flickerLights();
            }
        }
    }

}


As you see, there are two observers. The SoundEffectController, and the LightEffectController.

The SoundEffectController is class that manages the sound effects of the room. The light effect controller is a class that manages the lighting effects of the room.

Now, what we need is a way to associate these observers with the events with which they are interested- the change in the xCoordinate and yCoordinate of the Player. This is where the delegate function comes into the picture.

The delegate functions's primary purpose is to pass on control to all the interested Observers upon the occurrence of any event in the Observable object. This is the core function in the observer pattern. It is this function that allows you to have 2 flavors of the Observer pattern. We will first see the Push Model of the observer pattern.

The delegate function is defined in the Observable object. In order to make the delegate function do useful things, the methods that cause a change in the properties of the object, need to invoke the delegate function. Also, the Observable class needs to maintain a list of observers.

In the Push model, the delegate function iterates over each of these observers and passes the relevant information to the Observer. The following code demonstrates the new implementation of the player class using the push model.
And now, here is the new definition of the Player class which now implements the Observable interface.

public class Player implements Observable{
    
    private String name;
    private Integer xCooridinate;
    private Integer yCooridinate;

    private List observers ;

    public Player(String name) {
        this.name = name;
        this.observers=new ArrayList();
    }


    public Integer getxCooridinate() {
        return xCooridinate;
    }

    public Integer getyCooridinate() {
        return yCooridinate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void moveForward(Integer steps){
        xCooridinate+=steps;
        notifyObservers();
    }

    public void moveBackward(Integer steps){
        xCooridinate-=steps;
        notifyObservers();
    }

    public void jump(Integer height){
        yCooridinate+=height;
        notifyObservers();
    }

    public void fallTo(Integer height){
        yCooridinate=height;
        notifyObservers();
    }

    //This is the core function that delegates the change in the state of the
    //Observable object to the observers
    public void notifyObservers() {
        for(Observer o:observers){
            if(o instanceof SoundEffectController){
                o.update(yCooridinate);
            }
            else{
                if(o instanceof LightEffectController){
                    o.update(xCooridinate);
                }
            }
        }
    }

    public void addObserver(Observer o) {
        this.observers.add(o);
    }

    public void removeObserver(Observer o) {
        this.observers.remove(o);
    }
}


Here is the Main class.

public class Main {
    public static void main(String[] args){
        Player myDog = new Player("ScoobyDoo");

        myDog.addObserver(new SoundEffectController());
        myDog.addObserver(new LightEffectController());

        myDog.moveForward(2);
        System.out.println("Nothing yet.");
        myDog.moveForward(3);
        System.out.println("Nothing yet.");

        myDog.moveForward(7);
        
        myDog.jump(3);
        
    }
}


On running the main program, you get the following output.

Nothing yet.
Nothing yet.
Flicker the lights
Play an eerie sound


As is seen in the above code, it is clearly evident that the delegate function - notifyObservers() is invoking a particular function on an Observer to notify it of the changes in state. On close examination, you would notice that the delegate function is not as flexible as we want it to be. This is because, the delegate needs to be aware of the data that each observer is interested in listening to, thereby making the delegate function a tad more complex than it should be. As time progresses and more observers want to be notified of the changes in the Observable object, the delegate function becomes more convoluted as it needs to be aware of the requirements of each type of observer. For example, there may be 'n' number of observers interested in the change in the x coordinate of the player, while there may be 'm' number of observers that may be interested in the change of 'y' coordinate of the player. There might also be 'l' number of observers that may be interested in both the x and y coordinate of the player. The problem certainly becomes harder to solve as the variety and number of observers increases with time.


This is where the pull model comes to the rescue. In the pull model, the delegate function sends the Observable object itself to the Observers. It then becomes the observer's responsibility to extract the the information in which they are interested, from the Observable object. In our case, this can be implemented as follows.

Change the code in notifyObservers() in the Player class to the following


public void notifyObservers() {
        for(Observer o:observers){
                o.update(this);
        }
    }


Change the update function in SoundEffectControler to the following

public void update(Object o) {
        if(o instanceof Player){
            Player p = (Player)o;
            Integer yCoordiante = p.getyCooridinate();
            if(yCoordiante>0 && isSoundPlaying== false){
                playSound();
            }
        }
    }


Change the update function in LightEffectController to the following

public void update(Object o) {
        if(o instanceof Player){
            Player p = (Player)o;
            Integer xCoordiante = p.getxCooridinate();
            if(xCoordiante>10 && isLightFlickering==false){
                flickerLights();
            }
        }
    }


On running the main program, you get the following output.

Nothing yet.
Nothing yet.
Flicker the lights
Play an eerie sound


As you can see from the above code, the complexity has now shifted from the delegate function to the Observer classes. It is now the Observer's responsibility to take extract the information and also perform typecasting to identify the object with which it is being notified.

When you decide to implement the observer pattern, you keep in mind a few things. The push model works great in areas where you have several components that build up a system, and some of these components act as observers to many different types of Observable objects. In this case, you would prefer to provide only a specific portion of information to the observer instead of the entire Observable object. This would greatly increase the decoupling of your Observer components from the Observable components thereby giving you the chance to use the same observer across multiple objects.

The pull model works great if your Observable object is already in place and you are designing components around this Observable object. If there are many observers, and each observer depends of different combinations of the properties of the Observable object. In this case, since the components are being designed with only a particular Observable class in mind, shifting the complexity to the Observer classes seems like a good idea. Each observer would extract the relevant information from a Observable perform necessary actions.

As is the case with all design pattern, the way you choose to implement it depends on multiple factors. Understanding how a particular implementation will impact your solution should be the key concern in deciding upon a particular implementation.


Happy Programming :)
Signing Off
Ryan