var ZoneUpdater = function(spec) {
var elementId = spec.elementId;
var element = document.getElementById(elementId);
var url = spec.url;
var $zone = jQuery('#' + spec.zone);
var updateZone = function() {
var updatedUrl = url;
var params = {};
if (element.value) {
params.param = element.value;
}
$zone.tapestryZone('update', {
url : updatedUrl,
params : params
});
}
if (spec.event) {
var event = spec.event;
jQuery(element).bind(event, updateZone);
}
return {
updateZone : updateZone
};
}
Wednesday, March 16, 2011
ZoneUpdater - jQuery edition
Friday, May 21, 2010
Mixin to allow any element to submit a form and trigger an event
I changed it to a mixin and did some other minor changes.
@MixinAfter
@IncludeJavaScriptLibrary("AnySubmit.js")
public class AnySubmit {
/**
* The name of the event that will be triggered if this component is the cause of the form submission. The default
* is "selected".
*/
@Parameter(allowNull = false, defaultPrefix = BindingConstants.LITERAL)
private String event = EventConstants.SELECTED;
@Parameter(defaultPrefix = BindingConstants.LITERAL)
private String clientEvent = "change";
/**
* The value that will be made available to event handler method of this component when the form is
* submitted.
*/
@Parameter
private Object context;
/**
* If true (the default), then any notification sent by the component will be deferred until the end of the form
* submission (this is usually desirable).
*/
@Parameter
private boolean defer = true;
@InjectContainer
private ClientElement container;
@Inject
private ComponentResources resources;
@Inject
private RenderSupport renderSupport;
@Environmental
private FormSupport formSupport;
@Environmental
private Heartbeat heartbeat;
@Inject
private Request request;
@SuppressWarnings("serial")
private static class ProcessSubmission implements ComponentAction{
private final String clientId;
public ProcessSubmission(String clientId) {
this.clientId = clientId;
}
public void execute(AnySubmit component) {
component.processSubmission(clientId);
}
}
private void processSubmission(String clientId) {
String hiddenFieldName = clientId + ":hidden";
if (request.getParameter(hiddenFieldName) != null) {
final Object[] contextToPublish = getContext(request, clientId);
Runnable notification = new Runnable() {
public void run() {
resources.triggerEvent(event, contextToPublish, null);
}
};
if (defer)
formSupport.defer(notification);
else
heartbeat.defer(notification);
}
}
private Object[] getContext(Request request, String clientId) {
String contextFieldName = clientId + ":context";
String context = request.getParameter(contextFieldName);
if (context != null) {
return new Object[] { context };
}
String value = request.getParameter(clientId);
if (value != null) {
return new Object[] { value };
}
return null;
}
void beginRender() {
formSupport.store(this, new ProcessSubmission(container.getClientId()));
}
void afterRender(MarkupWriter writer) {
renderSupport.addInit("anySubmit", formSupport.getClientId(), container.getClientId(), clientEvent);
if (context != null) {
writer.element("input", "type", "hidden", "value", context, "name", container.getClientId() + ":context");
writer.end();
}
}
}
Tapestry.AnySubmit = Class.create({
initialize: function(formId, clientId, event)
{
this.form = $(formId);
this.element = $(clientId);
this.element.observe(event, this.onEvent.bindAsEventListener(this));
},
createHidden : function()
{
var hidden = new Element("input", { "type":"hidden",
"name": this.element.id + ":hidden",
"value": this.element.id});
this.element.insert({after:hidden});
},
onEvent : function(event)
{
Event.stop(event);
var onsubmit = this.form.onsubmit;
if (onsubmit == undefined || onsubmit.call(window.document, event))
{
this.createHidden();
this.form.submit();
}
return false;
}
});
Tapestry.Initializer.anySubmit = function(formId, clientId, event)
{
new Tapestry.AnySubmit(formId, clientId, event);
}
Monday, March 15, 2010
Check all mixin
Example: <input type="checkkbox" t:type="any" t:mixins="checkall" t:controlledClass="element-selected"/>
CheckAll.java
/**
* Mixin for checkboxes that should control the checked state of a group of other checkboxes. All the controlled checkboxes need to
* have the CSS class specified in thecontrolledClass
parameter.
*
* @author Inge
*
*/
public class CheckAll {
/**
* The controller checkbox that this mixin applies to.
*/
@InjectContainer
private ClientElement container;
@Environmental
private RenderSupport renderSupport;
/**
* The CSS class that all controlled checkboxes must have to be controlled by the master checkbox.
*/
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String controlledClass;
void afterRender() {
renderSupport.addScript("new CheckAll('%s', '%s')", container.getClientId(), controlledClass);
}
}
CheckAll.js
var CheckAll = Class.create( {
initialize : function(controllerId, controlledClass) {
this.controller = $(controllerId);
this.controlledClass = controlledClass;
this.controller.observe('change', this.toggle.bindAsEventListener(this));
},
toggle: function() {
var checked = this.controller.checked;
var controlledCheckboxes = $$('input.' + this.controlledClass);
controlledCheckboxes.each(function(checkbox) {
checkbox.checked = checked;
});
}
});
Friday, March 5, 2010
New and better (?) ZoneUpdater
I also wanted to add a missing feature, the ability to update a zone simply by calling a javascript function. This is a nice way of "object orienting" different features/sections on a page, by giving different sections their own client API that they can communicate with.
Most important changes:
- Removed support for specifying another listening element than the container
- Cleaner code
- Request parameter instead of encoding parameter into link context.
- Generates a javascript variable to easy zone update through javascript.
I also wanted to add an internal listener that triggers the actual event with context, so the page/component listener doesn't have to inject the Request and do request.getParameter("param"). Didn't succeed so far.
Anyway, here's the modified code. No code formatting this time, but it should be short enough to be readable. Enjoy :)
ZoneUpdater.java
@IncludeJavaScriptLibrary( { "ZoneUpdater.js" })
public class ZoneUpdater {
@Inject
private ComponentResources resources;
@Environmental
private RenderSupport renderSupport;
/**
* The event to listen for on the client. If not specified, zone update can only be triggered manually through calling updateZone on the JS object.
*/
@Parameter(defaultPrefix = BindingConstants.LITERAL)
private String clientEvent;
/**
* The event to listen for in your component class
*/
@Parameter(defaultPrefix = BindingConstants.LITERAL, required = true)
private String event;
@Parameter(defaultPrefix = BindingConstants.LITERAL, value = "default")
private String prefix;
/**
* The element we attach ourselves to
*/
@InjectContainer
private ClientElement element;
@Parameter
private Object[] context;
/**
* The zone to be updated by us.
*/
@Parameter(defaultPrefix = BindingConstants.LITERAL, required = true)
private String zone;
void afterRender() {
String url = resources.createEventLink(event, context).toAbsoluteURI();
String elementId = element.getClientId();
JSONObject spec = new JSONObject();
spec.put("url", url);
spec.put("elementId", elementId);
spec.put("event", clientEvent);
spec.put("zone", zone);
renderSupport.addScript("%sZoneUpdater = new ZoneUpdater(%s)", prefix, spec.toString());
}
}
ZoneUpdater.js
var ZoneUpdater = Class.create({
initialize: function(spec) {
this.element = $(spec.elementId);
this.url = spec.url;
$T(this.element).zoneId = spec.zone;
if (spec.event) {
this.event = spec.event;
this.element.observe(this.event, this.updateZone.bindAsEventListener(this));
}
},
updateZone: function() {
var zoneManager = Tapestry.findZoneManager(this.element);
if ( !zoneManager ) return;
var updatedUrl = this.url;
if (this.element.value) {
var param = this.element.value;
if (param) {
updatedUrl = addParameter('param', param, updatedUrl); // You need to provide your own function for this...
}
}
zoneManager.updateFromURL(updatedUrl);
}
});
Tuesday, October 20, 2009
Link with confirmation
This is a component that adds confirmation to a regular EventLink. It does this by using the TapestryExt.js library introduced in my previous post to trigger a link after intercepting and cancelling it first. It works both with and without zones.
It is used excactly like an EventLink, with an additional “message” parameter, to display in confirmation box.
For now, I only implemented a standard javascript confirm box. But it shouldn’t be too hard extending this with more fancy interaction with DHTML.
I’m not completely comfortable with the techniques used here. Some of it looks a lot like a hack in my opinion, especially the part about intercepting/cancelling a zone listener and re-adding it afterwards using copy-paste from tapestry.js.
ConfirmLink.java:
/**
* Displays a javascript confirmation box before actually triggering the link.** @author Inge**/@IncludeJavaScriptLibrary({"TapestryExt.js, "ConfirmLink.js"})public class ConfirmLink implements ClientElement {@Environmentalprivate RenderSupport renderSupport;@Parameter("literal:Do you really want to delete?")private String message;@Component(publishParameters="event,zone,context", inheritInformalParameters=true)private EventLink confirmLink;void afterRender() {String url = confirmLink.getLink().toRedirectURI();renderSupport.addScript("new ConfirmLink('%s', '%s', '%s')", confirmLink.getClientId(), url, message);}public String getClientId() {return confirmLink.getClientId();}}
ConfirmLink.js
var ConfirmLink = Class.create({initialize: function(element, url, message) {this.element = $(element);this.url = url;this.message = message;this.initListeners = this.initListeners.bind(this);this.initListeners.defer();// Makes it run after Tapestry:init to be able to delete// zone listener added by Tapestry and start listening for// our modded version instead.},onclick: function(event) {Event.stop(event);if (confirm(this.message)) {TapestryExt.triggerLink(this.element, this.url);}},initListeners: function() {this.element.stopObserving('click'); // Remove zone update, will be re-added later by TapestryExt.js.this.element.observe('click', this.onclick.bindAsEventListener(this));}});
Friday, October 16, 2009
Missing javascript
I think there are some important things missing from Tapestry.js to release the full potential of Tapetsry 5 and AJAX. I have started working on a javascript class, TapestryExt, that extends the functionality of Tapestry.js.
My wish is to see all of this and more built in to tapestry.
/**
* Commonly needed functions that are absent in the default Tapestry js lib.*/var TapestryExt = {/**
* If the specified form listens for the Tapestry.FORM_PROCESS_SUBMIT_EVENT event* (all forms with a zone specified do), it will AJAX-submit and update its zone after.*/submitZoneForm : function(element) {element = $(element)if (!element) {Tapestry.error('Could not find form to trigger AJAX submit on');return;}element.fire(Tapestry.FORM_PROCESS_SUBMIT_EVENT);},/**
* Trigger any link, zone or not.** If no url is provided, the href attribute of element will be used.*/triggerLink : function(element, url) {element = $(element);if (!url) {url = element.href;}if (!url) {Tapestry.error('Unable to find url to trigger on element ' + element.id);}var zoneObject = Tapestry.findZoneManager(element);if (zoneObject) {zoneObject.updateFromURL(url);}else {// Regular link// Note: this will skip all event observers on this link!window.location.href = url;}}}
Thursday, May 21, 2009
Simple OnEvent mixin
This mixin is heavily based on Chenillekit OnEvent. I found that CK’s mixin had a different and too specific focus to fit my needs. I wanted to write an event mixin that does nothing but trigger an event. This is what I came up with, I believe the result is quite easy to understand, and should work as a nice foundation for other similar components and mixins.
Usage:
<input type=”button” value=”Answer yes” t:type=”any” t:id=”yesButton” t:mixins=”onEvent” t:event=”click” callback=”updateStatus”/>
Object onClickFromYesButton() {
return “Positive”; // Arguments for javascript function “updateStatus”
}
OnEvent.java
@IncludeJavaScriptLibrary("OnEvent.js")public class OnEvent {@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)private String event;@Parameterprivate Object[] context;@Environmentalprivate RenderSupport renderSupport;@InjectContainerprivate ClientElement container;@Parameter(defaultPrefix = BindingConstants.LITERAL)private String callback;@Injectprivate ComponentResources componentResources;void afterRender() {Link link = componentResources.createEventLink(event, context);String script = "new OnEvent('%s', '%s', '%s', '%s')";renderSupport.addScript(script, container.getClientId(), event, link.toRedirectURI(), callback);}}
OnEvent.js
var OnEvent = Class.create({initialize: function(elementId, event, url, callback){if (!$(elementId))throw(elementId + " doesn't exist!");this.element = $(elementId);this.callback = callback;this.url = url;this.element.observe(event, this.eventHandler.bindAsEventListener(this));},eventHandler: function(event){new Ajax.Request(this.url, {method: 'get',onFailure: function(t){alert('Error communication with the server: ' + t.responseText.stripTags());},onException: function(t, exception){alert('Error communication with the server: ' + exception.message);},onSuccess: function(t){if (this.callback){var funcToEval = this.callback + "(" + t.responseText + ")";eval(funcToEval);}}.bind(this)});}});