Message Boards

Encapsulating Javascript for the current page only

thumbnail
Dominik Marks, modified 4 Years ago.

Encapsulating Javascript for the current page only

Regular Member Posts: 149 Join Date: 8/29/12 Recent Posts
To execute specific Javascript when a user navigates to a page, we use a Javascript which looks as follows:
<script>
  Liferay.on('endNavigate', function() { //do something });
</script>
However we want to execute this on a specific page only.So for example if the above script is present on "Page A" only, it is executed when a user navigates to that page. But it is also executed when a user navigates away from "Page A" to "Page B".Any idea why this is happening? How can I encapsulate the script so that it is only executed when a user navigates to the page and not when the user navigates away from the page?The above code is being used in Liferay 7.0.6 GA7.
thumbnail
Olaf Kock, modified 4 Years ago.

RE: Encapsulating Javascript for the current page only

Liferay Legend Posts: 6403 Join Date: 9/23/08 Recent Posts
Dominik Marks:

However we want to execute this on a specific page only.So for example if the above script is present on "Page A" only, it is executed when a user navigates to that page. But it is also executed when a user navigates away from "Page A" to "Page B".Any idea why this is happening?
My guess: SPA. Once the event handler is registered, the page is never changed, and the event is triggered every time. You can unregister it right after it fires, or check for the current page in Javascript. Note: If you navigate to the page multiple times, you might register the same callback multiple times. The magic of SPA - I've been bitten by it a couple of times emoticon