1

The struts 2 jQuery plugin has a built in publish/subscribe framework.

If you define your own publish and subscribe event (for example on a grid) the subscribed function will be called every time the event is published. For details please see (Struts 2 jQuery Subscribe is called more than once)

To prevent this, there is a isSubscribed method which can be used.

For a grid as:

<sjg:grid id="gridtable" 
        onBeforeTopics="before_grid_load" >

The JS will be:

$.subscribe('before_grid_load', function(event, data) {     

    if ( $('#gridtable').isSubscribed('before_grid_load') ){
      return ;    
    }
//go on with function
}

The problem is that the $('#gridtable').isSubscribed('before_grid_load') returns false every time!

Community
  • 1
  • 1
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173

2 Answers2

2

The function isSubscribed is applied on the element $('#gridtable') but subscribed to the $(document). I have tested with the last element and it didn't work to me. But tried with the first element and it worked.

Script:

<head>
  <link href="<s:url value="/css/template_styles.css"/>" type="text/css" rel="stylesheet">
  <sj:head />
  <title>jQuery Grid</title>
  <script type="text/javascript">
    $(document).ready(function(){
    console.log("Before subscribe");
    $("#gridtable").subscribe("beforeTopic", function(topic, data) {
      console.log('Topic: '+data, topic);
      if ( $("#gridtable").isSubscribed("beforeTopic") ){
        console.log('Subscribed: '+data, topic);
        return;
      }
      //go on with function
      console.log('Not subscribed: '+data, topic);
    });
    console.log("After subscribe");
    });
    </script>
</head>

For grid:

<sjg:grid id="gridtable" 
        onBeforeTopics="beforeTopic" >
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • Thanks! Just a note: When the `beforeTopic` is published `$("#gridtable").subscribe("beforeTopic..."` will be called only once while the `$.subscribe("beforeTopic...."` will be called for every grid which has published that event. So with this solution there is no need to call `isSubscribed` any more. – Alireza Fattahi May 17 '14 at 15:31
  • 1
    Generally speaking you can call `isSubscribed` in any other place, not exactly in the topic handler, where as you have mentioned it's useless, so to make sure if an element is subscribed to the topic you can check it on that element. – Roman C May 17 '14 at 16:23
  • Another solution can be found at: http://stackoverflow.com/questions/20441178/struts-2-jquery-subscribe-is-called-more-than-once/34291480#34291480 You can `return false` at the end of subscribe – Alireza Fattahi Dec 16 '15 at 06:38
0

Check your lib to your jsp

<%@ taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>

Enable jQuery Grid Plugin in your Head Tag

 <sj:head jqueryui="true" jquerytheme="redmond" />
hari
  • 1,874
  • 1
  • 16
  • 10