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)});}});
No comments:
Post a Comment