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;
  @Parameter
  private Object[] context;
  @Environmental
  private RenderSupport renderSupport;
  @InjectContainer
  private ClientElement container;
  @Parameter(defaultPrefix = BindingConstants.LITERAL)
  private String callback;
  @Inject
  private 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)
        });
    }
});

No comments:

Post a Comment