Tapestry 5.4 call jquery more than once

2019-08-06 20:01发布

问题:

I am trying to integrate Bootstrap popover to my Tapestry 5.4-alpha-14 application. I am new to Tapestry, and I am not sure how to use javascript there.

My problem is that I want to show Bootstrap popover on each element in a zone loop when the zone is refreshed. First I have no elements in the zone, then the user submits a form and an element is loaded, and then some more user interaction, and another element is loaded, and so on... I want to show the popover on each loaded element in the loop. With the code bellow I was able to show the popover only when the first element was loaded, but then when the second is loaded the popover was lost. I also notice that the .js code was not called on the second load.

Part of the .tml code:

<t:zone t:id="selectedPagesZone" id="selectedPagesZone">
 <div class="well" t:type="Loop" t:id="selectedLoop" t:source="selectedPages" t:value="item">
    <div class="pop" data-toggle="popover" rel="popover" data-placement="top"  data-container="body" data-content="Content" title="Title">
        ...
     </div>
   </div>
</t:zone>

Part of the .java code:

void onSuccess() {
...
ajaxResponseRenderer.addRender(selectedPagesZone).ajaxResponseRenderer.addCallback(new JavaScriptCallback() {
   public void run(JavaScriptSupport javaScriptSupport) {
      javaScriptSupport.require("popover");
    }
});

The popover.js code:

(function ($) {
options = {
    placement:'right',
    trigger: 'hover',
    container: 'body',
    html: true
  }
$('.pop').popover(options);
$('.pop').popover('show');
})(window.jQuery);

I would appreciate any help you can give me.

回答1:

require.js will only execute the body of your js once. You should define a function which is configured once but executed multiple times.

popover.js

define(["jquery"], function($) {
    var privateFunc = function(args) {
        options = {
            placement:'right',
            trigger: 'hover',
            container: 'body',
            html: true
        };
        $('.pop').popover(options);
        $('.pop').popover('show');
    };
    return { publicFunc: privateFunc};
});

java code

ajaxResponseRenderer.addCallback(new JavaScriptCallback() {
    public void run(JavaScriptSupport javaScriptSupport) {
        JSONObject args = new JSONObject("foo", "bar");
        javaScriptSupport.require("popover").invoke("publicFunc").with(args);
    }
});

See here for more info