Chapter 44. Script Code Examples
44.1. Accessing a module from a script
To access a module from a script, RequireJS uses the
require function to execute a function in the managed context:
require([“SHARED/ModuleA”], function(a) { // Codes of interacting with module A a.doSomething(); });
As shown above, use the AMD module name of the module that depend on,
PORTLET/ModuleA. The prefix in upper case is the module scope which has a value SHARED , PORTLET, or PORTAL .
44.2. Exposing jQuery Version Globally
The built-in jQuery is declared as an AMD module. By default jQuery is not available in the window object of the browser. This example shows how to make it available and allow to write code in a plain script.
The following script makes jQuery available by mounting the jQuery object in the window object:
require( [“SHARED/jquery”], function($) { // the ‘$’ in window.$ is alias, you can make the other for yourself. window.$ = $; });
This script must be integrated as a shared script:
<scripts> <name>imediatejs</name> <script> <path>/myfolder/imediateJScript.js</path> </script> </scripts>
A portlet then provide its own script that depends on the script written above:
<portlet> <name>foo</name> <script> <name>portletjs</name> <path>/myfolder/portlet.js</path> </script> <depends> <scripts>imediatejs</scripts> </depends> </scripts>
The JavaScript is as follows:
$("#foo").html("<h1>hello global jQuery</h1>");
44.3. Defining a custom global jQuery
Define a globally-available custom jQuery by reusing existing code, and combine them by:
- Using a custom jQuery version.
- Exposing the portal version of jQuery globally.
44.4. Using a Global jQuery plugin
To implement this example the global jQuery is available should be available before the global jQuery plugin is loaded.
Now, you know scoping a module to a portlet and that the module is loaded when the portlet is on a page using the
PORTLET scope.
In this example change the scope and use
PORTAL. The main difference is that the loading of your plugin is triggered on a specific portal instead of a specific portlet.
Procedure 44.1. Using a global jQuery plugin
- Create a jQuery plugin as a script named
myPlugin.jsand integrate your plugin. require([“SHARED/jquery”], function($) { $.fn.myPluginFunction = function() { // Your work here; }; });
- Bind the script in the portal and reuse the
immediate.jsscript seen before: <portal> <name>classic</name> <scripts> <script> <name>myPlugin</name> <path>/myfolder/myPlugin.js</path> </script> <script> <name>imediatejs</name> <path>/myfolder/imediateJScript.js</path> </script> </scripts> </portal>
- The plugin is globally available to use:
<script type=”text/javascript”> $(‘#foo’).myPluginFunction(); </script>