What's the approach to add javascript to a Tapestry application?
Asked Answered
F

1

7

I'm starting with an existing webapp built with Tapestry.

I can't figure out where to put the Javascript I need.

Basically this application has a single page capturing data into a text area, and I want to include a javascript library to do something with that text area.

What's the approach to add javascript to a Tapestry app? Any sample or link would be much appreciated.

Chau! :)

Facer answered 19/8, 2010 at 22:15 Comment(0)
C
4

To add some client-side behaviour to a component, you usually create a component mixin class in the mixins package of your app:

package my.tapestry.basepackage.mixins;

public class TextAreaResizer {

}

In your component template, you add the mixin to your text area like this:

<textarea t:type="TextArea" t:value="..." t:mixins="TextAreaResizer" />

To load a JS library into a page, you can use the @IncludeJavaScriptLibrary annotation on your mixin, like this:

@IncludeJavaScriptLibrary("context:textarearesizer/js/textarearesizer.js")
public class TextAreaResizer {

}

If you need to run some initialization code, that's done through the RenderSupport service, like this:

@IncludeStylesheet("context:textarearesizer/css/textarearesizer.css")
@IncludeJavaScriptLibrary("context:textarearesizer/js/textarearesizer.js")
public class TextAreaResizer {

    @Inject
    private RenderSupport renderSupport;

    @InjectContainer
    private TextArea textArea;

    @AfterRender
    void addScript() {
        this.renderSupport.addScript(
             "new TextAreaResizer('%s');", this.textArea.getClientId());
    }

}

In this case, I have also injected the text field component into the mixin class because I need its client ID.

Also check out the AJAX & Javascript section of the T5 docs.

Coloration answered 20/8, 2010 at 7:48 Comment(2)
Wow!!.. I'll give it a try. Thanks for the answer. ( I wonder why I didn't see your answer before )Facer
I am trying to create a small JS script that utilises a variable in my component's java class (find all instances of $string in page and highlight them). Should I use the first approach, and then write JavaScript into eg public class TextHighlighter? Or should I write it into a JS file, include that @IncludeJavaScriptLibrary("texthighlighter.js") and then somehow pass the variable from the java class to the JS?Tsarina

© 2022 - 2024 — McMap. All rights reserved.