Great one, thank you...

Andy



Inge Solvoll schrieb:
Hi!

I would like to share another mixin with you guys. Most of you probably know
how easy it is to create these, but maybe this can help beginners in
understanding things. I really love the mixin concept, it makes it so very
very easy to separate concerns in the view layer.

The mixin code below prevents the user from entering more in a text field
than you want him to do. It adds a required "max" parameter to the
containing component, which can be any input element with a value property,
really. But it probably only makes sense in a text field and a text area. An
optional counter box is displayed below the textarea, for keeping track of
remaining space.

USAGE: <textarea t:type="textarea" value="someProperty" rows="9"
t:mixins="maxlength" max="50"

/**
 * Enforces maxlength on a textfield or a textarea
 *
 * @author Inge
 *
 */
@IncludeJavaScriptLibrary("MaxLength.js")
public class MaxLength {

  @InjectContainer
  private ClientElement container;

  @Parameter(required=true)
  private int max;

  @Parameter("true")
  private boolean displayCounter;

  @Environmental
  private RenderSupport renderSupport;

  void afterRender(MarkupWriter writer) {
    String id = container.getClientId();
    writer.element("div", "id", id + "-counter-container");
    if (!displayCounter) {
      writer.attributes("style", "display: none");
    }
    writer.element("input", "type", "text", "id", id + "-counter",
"disabled", "disabled", "size", "3");
    writer.end();
    writer.end();
    renderSupport.addScript("new MaxLength('%s', %s)", id, max);
  }
}

Javascript MaxLength.js, put in the same package as the java file:

var MaxLength = Class.create();

MaxLength.prototype = {
    initialize: function(id, max) {
        this.max = max;
        this.element = $(id);
        this.element.observe('keyup', this.keyup.bindAsEventListener(this));
        this.counterElement = $(id + "_counter");
        this.updateCounter();
    },
    keyup: function(event) {
        if (this.element.value.length > this.max) {
            this.element.value = this.element.value.substring(0, this.max);
        }
        this.updateCounter();
    },
    updateCounter: function() {
        var currentLength = this.element.value.length;
        this.counterElement.value = (this.max - currentLength);
    }
}



---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@tapestry.apache.org
For additional commands, e-mail: users-h...@tapestry.apache.org

Reply via email to