tapestry與可重複使用的javaScript,實現方法是給函數傳變量,代碼以下:javascript
ReusableJavaScript.javahtml
/**
* 項目名稱:TapestryStart
* 開發模式:Maven+Tapestry5.x+Tapestry-hibernate+Mysql
* 版本:1.0
* 編寫:飛風
* 時間:2012-02-29
*/
package com.tapestry.app.pages;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
@Import(library="context:assets/js/textbox_hint.js")
public class ReusableJavaScript {
@Property
@SuppressWarnings("unused")
private String firstName;
@Property
@SuppressWarnings("unused")
private String lastName;
@Inject
private JavaScriptSupport javaScriptSupport;
public void setupRender() {
javaScriptSupport.addScript(String.format("new TextboxHint('%s', '%s', '%s');", "firstName",
"Enter First Name", "#ff6600"));
javaScriptSupport.addScript(String.format("new TextboxHint('%s', '%s', '%s');", "lastName", "Enter Last Name",
"blue"));
}
}
ReusableJavaScript.tmljava
<html t:type="layout" title="tapestryStart Index" t:sidebarTitle="Framework Version"
xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd" xmlns:p="tapestry:parameter">
<form t:type="form" t:autofocus="false">
<input t:type="TextField" t:id="firstName"/>
<input t:type="TextField" t:id="lastName"/><br/>
</form>
</html>
textbox_hint.jssql
TextboxHint = Class.create( {
initialize : function(textboxId, hintText, hintColor) {
this.textbox = $(textboxId);
this.hintText = hintText;
this.hintColor = hintColor;
this.normalColor = this.textbox.getStyle('color');
Event.observe(this.textbox, 'focus', this.doClearHint.bindAsEventListener(this));
Event.observe(this.textbox, 'blur', this.doCheckHint.bindAsEventListener(this));
Event.observe(this.textbox, 'change', this.doCheckHint.bindAsEventListener(this));
Event.observe(this.textbox.form, 'submit', this.doClearHint.bindAsEventListener(this));
this.doCheckHint();
},
doClearHint : function(e) {
if (this.textbox.value == this.hintText) {
this.textbox.value = "";
}
this.textbox.setStyle({color: this.normalColor});
},
doCheckHint : function(e) {
// If field is empty, put the hintText in it and set its color to hintColor
if (this.textbox.value.length == 0) {
this.textbox.value = this.hintText;
this.textbox.setStyle({color: this.hintColor});
}
// Else if field contains hintText, set its color to hintColor
else if (this.textbox.value == this.hintText) {
this.textbox.setStyle({color: this.hintColor});
}
// Else, set the field's color to its normal color
else {
this.textbox.setStyle({color: this.normalColor});
}
}
} )