Wicketing Javascript through AJAX

No Comments »

Communication between Java and Javascript cannot be done easier than with Wicket framework, by far the best helper if you’re in Java based web development.

html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns:wicket>
<head>
<script type="text/javascript" >
function callWicket() {
	wicketAjaxGet(callback + '&parameter=value', function() {}, function() {});
}
</script>
</head>

<body>
	<div wicket:id = "div"></div>
	<span wicket:id = "wicketAnswer">[]</span>
</body>
</html>

Java - or should I say the magic of Wicket?

package com.somepackage;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.util.time.Duration;

@SuppressWarnings("serial")
public class BasePage extends WebPage {
	private WebMarkupContainer dummyDiv;
	private Label label;

	public BasePage() {
		this(null);
	}

	public BasePage(final PageParameters parameters) {
		//handle js call to wicket
		final AbstractDefaultAjaxBehavior behavior = new AbstractDefaultAjaxBehavior() {
		    protected void respond(final AjaxRequestTarget target) {
		    	label.setModelObject("Yeah I was just called from Javascript!");
		        target.addComponent(label);
		    }
		};
		add(dummyDiv = new MyWebMarkupContainer("div", behavior));
		//handle wicket call to js
		dummyDiv.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)) {
			@Override
			protected void onPostProcessTarget(AjaxRequestTarget target) {
				target.appendJavascript("callWicket();");
			}
		});
		dummyDiv.add(behavior);

    	add(label = new Label("wicketAnswer", "Look here to see when wicket is called from javascript"));
    	label.setOutputMarkupId(true);
	}
}

@SuppressWarnings("serial")
class MyWebMarkupContainer extends WebMarkupContainer implements IHeaderContributor {
	AbstractDefaultAjaxBehavior behavior;

	public MyWebMarkupContainer(String id, AbstractDefaultAjaxBehavior behavior) {
		super(id);
		this.behavior = behavior;
	}

	@Override
	public void renderHead(IHeaderResponse response) {
		response.renderJavascript("var callback = '" + behavior.getCallbackUrl() + "';", "insertedjavascript");
	}
}

I don’t think anyone needs explanation about how this works since it’s THAT easy. Only one more thing to add:

Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();

- this to get the parameters map.

Javascript inheritance

No Comments »

When it comes to web development, Javascript is the best client-side programming language. It has come a long way in the last years. It’s no longer just a simple scripting language. These days a lot of Javascript libraries are available to be used freely and they are incredibly powerful: Script.aculo.us, DOJO, YUI, jQuery, Prototype, to name just a few.

I am personally not very found of Javascript because of its loosely typed nature. I consider it harder to develop a large framework in Javascript compared to say, Java, because the compiler/interpreter cannot always come to your rescue as you’d expect if you’re coming from a strongly typed language.

But a lot of its strength comes from the fact that it’s loosely typed. You also feel the sense of freedom that only these kind of languages (like Ruby) can offer. Types help you a lot to avoid errors and to give you important structure, but also constrain your ability to do more with your code.

Javascript is (or can act like) a(n almost) full fledged object oriented language. Let’s try inheritance:

This is the method that simulates inheritance in Javascript:

function inherit(child, parent) {
    var sConstructor = parent.toString();
    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
    if ( aMatch != null ) { child.prototype[aMatch[1]] = parent; }
    for (var m in parent.prototype) {
        child.prototype[m] = parent.prototype[m];
    }
};

Let’s define some Javascript objects:

function Element() {
	this.location = null;
	this.type = "Element";
	this.selected = false;
	this.zIndex = 0;
}
Element.prototype.isInside = function(rectangle){
        dosomething;
}

function Item() {
	this.Element(); //calling the constructor of the base class

	this.lastValidLocation = null; //a rectangle
	this.type = "Item";
	this.selectorItem = null;
	this.zIndex = 1;
}
inherit(Item, Element);
Item.prototype.getSelectorItem = function() {
	return this.selectorItem;
}
Item.prototype.draw = function() {
       dosomething;
}
Item.prototype.deleteItem = function() {
       dosomething;
}

function SelectorItem() {
	this.Element();

	this.items = new Array();
	this.type = "SelectorItem";
	this.zIndex = 0;
}
inherit(SelectorItem, Element);
SelectorItem.prototype.getSelectorItem = function() {
	return this;
}
SelectorItem.prototype.createNewItem = function(onItem) {
       dosomething;
}
SelectorItem.prototype.draw = function() {
       dosomething;
}

It is very important when you call “inherit”. That’s because Javascript does not support method override/overload, but you can also simulate this. When executing “inherit”, the prototype of the base class will be copied to the child. Then, if needed, redefine some methods so that when you call them, the new ones will get executed.

Using a static image map with Wicket

No Comments »

On one of my projects I had to implement an image and link the image area to wicket.

This is how I did it:

html

<div>
   <map name="themap">
       <area shape="rect" coords="a1,b1,c1,d1" href="#"
           wicket:id="wicket1" title="Title1" />
       <area shape="rect" coords="a2,b2,c2,d2" href="#"
           wicket:id="wicket2" title="Title2" />
   </map>
   <br/>
   Some text here
</div>

Java

       add(new PageLink("wicket1", SomeWicketClass1.class));
       add(new PageLink("wicket2", SomeWicketClass2.class));

Wicket is the best framework for web development.

Javascript - how to make something happen after some time

No Comments »

I’m writing this post because I’ve been asked a million times about this and it’s easier to point someone to a link than to explain it again :-) .

In Javascript, executing something after a specified time couldn’t be easier - you’ve got the setTimeout method. Just be careful to call it the right way. It takes two arguments:

-> the method to be called after the specified time passed. I repeat, a method, not a method call.
-> the amount of time, specified in milliseconds.

For example, using script.aculo.us, I can make the “feedback” div fade away in 10 seconds after rendering like this:

window.setTimeout(function() {Effect.Fade(’feedback’);}, 10000);

(and NOT window.setTimeout(Effect.Fade(’feedback’), 10000}; - also keep in mind Javascript is case sensitive)