Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This is a slight extension of Passing HTTP parameters to Ajax callback methods to answer a specific usecase.

Stipulating that you have an element with wicket:id 'body':

From Java code able to access that element within scope:

Code Block
//...(class declarations)
final static String KEYPRESS_PARAM = "keyPressed";
//...
private void handleA(){}//Desired behavior when 'a' is pressed on the client
private void handleB(){}//Desired behavior when 'b' is pressed on the client
public void someSetupMethod(){
body.add(new AjaxEventBehavior("onkeypress"){
		    	@Override
				protected CharSequence getCallbackScript(boolean onlyTargetActivePage)
				{
					return generateCallbackScript("wicketAjaxGet('"+getCallbackUrl(onlyTargetActivePage)+"&"+KEYPRESS_PARAM+"='+wicketKeyCode(event)");
				}
				@Override
				protected void onEvent(AjaxRequestTarget target) {
					 String paramValue = RequestCycle.get().getRequest().getParameter(KEYPRESS_PARAM);
					 try{//The key parameter is the pressed keychar's ascii value
						 int key = Integer.parseInt(paramValue);
						 switch(key){
							 case 'a':
								 handleA();
							 break;
							 case 'b':
								 handleB();
							 break;
						 }
					 }
					 catch(NumberFormatException e){//Catches the possibly null parameter, or malformation.
						 return;//You might handle this a bit more responsibly.
					 }
				}	
	    	});
//...
}