Wednesday, April 15, 2009

Open a page in a popup window

This mixin can be applied to any element that has an onclick event. It opens the specified page in a new window. There is room for more parameters here for styling the window, and possibly for using other events than onclick as a trigger.

Usage:

<input type=”button” value=”View shopping cart” t:mixins=”popupPageLink” page=”cart/view” context=”cartId”/>

Java:

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
@IncludeJavaScriptLibrary("PopupPageLink.js")
public class PopupPageLink {
  @Inject
  private ComponentResources resources;
  @Environmental
  private RenderSupport renderSupport;
  @InjectContainer
  private ClientElement container;
  @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
  private String page;
  
  @Parameter(defaultPrefix = BindingConstants.LITERAL, value="800")
  private String width;
  
  @Parameter(defaultPrefix = BindingConstants.LITERAL, value="600")
  private String height;
  @Parameter
  private Object[] context;
  void afterRender() {
    Link link = resources.createPageLink(page, true, context);
    renderSupport.addScript("new PopupPageLink('%s', '%s', %s, %s);", container.getClientId(), link, width, height);
  }
}


Javascript:



var PopupPageLink = Class.create();
PopupPageLink.prototype = {
	initialize: function(id, link, width, height) {
		this.element = $(id);
		this.link = link;
		this.width = width;
		this.height = height;
		Event.observe(this.element, 'click', this.onclick.bindAsEventListener(this));
	},
	onclick: function() {
		var	name = 'dialogWindow';
		var win = window.open(this.link,name,'width=' + this.width + ',height=' + this.height + ',resizable=yes,scrollbars=yes,menubar=no,screenX=0,screenY=0,left=0,top=0' );
	    win.focus();
	}
}

5 comments:

  1. Nice. A usage example would complete this post.

    ReplyDelete
  2. Thanks for the feedback! I will edit the post right away with a usage example.

    ReplyDelete
  3. resources.createPageLink is deprecated.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. It's a very good mixin!

    To avoid createPageLink deprecation, you should @Inject PageRenderLinkSource and call createPageRenderLink or createPageRenderLinkWithContext (on afterRender()), depending on Context parameter value.

    Btw, great blog! I bookmarked it as a T5 help reference =)

    ReplyDelete