You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tapestry.apache.org by bu...@apache.org on 2014/06/02 19:19:32 UTC

svn commit: r910965 - in /websites/production/tapestry/content: cache/main.pageCache javascript-modules.data/ javascript-modules.data/Tapestry_Integration_Test_Application_and_JavaScriptSupport__Tapestry_API_Documentation_.png javascript-modules.html

Author: buildbot
Date: Mon Jun  2 17:19:31 2014
New Revision: 910965

Log:
Production update by buildbot for tapestry

Added:
    websites/production/tapestry/content/javascript-modules.data/
    websites/production/tapestry/content/javascript-modules.data/Tapestry_Integration_Test_Application_and_JavaScriptSupport__Tapestry_API_Documentation_.png   (with props)
    websites/production/tapestry/content/javascript-modules.html
Modified:
    websites/production/tapestry/content/cache/main.pageCache

Modified: websites/production/tapestry/content/cache/main.pageCache
==============================================================================
Binary files - no diff available.

Added: websites/production/tapestry/content/javascript-modules.data/Tapestry_Integration_Test_Application_and_JavaScriptSupport__Tapestry_API_Documentation_.png
==============================================================================
Binary file - no diff available.

Propchange: websites/production/tapestry/content/javascript-modules.data/Tapestry_Integration_Test_Application_and_JavaScriptSupport__Tapestry_API_Documentation_.png
------------------------------------------------------------------------------
    svn:mime-type = image/png

Added: websites/production/tapestry/content/javascript-modules.html
==============================================================================
--- websites/production/tapestry/content/javascript-modules.html (added)
+++ websites/production/tapestry/content/javascript-modules.html Mon Jun  2 17:19:31 2014
@@ -0,0 +1,177 @@
+<!DOCTYPE html>
+	
+	<!--
+
+    Licensed to the Apache Software Foundation (ASF) under one or more
+    contributor license agreements.  See the NOTICE file distributed with
+    this work for additional information regarding copyright ownership.
+    The ASF licenses this file to You under the Apache License, Version 2.0
+    (the "License"); you may not use this file except in compliance with
+    the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing, software
+    distributed under the License is distributed on an "AS IS" BASIS,
+    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+    See the License for the specific language governing permissions and
+    limitations under the License.
+-->
+<html>
+<head>
+  <meta http-equiv="x-ua-compatible" content="IE=9">
+  <title>
+    JavaScript Modules -- Apache Tapestry
+  </title>
+  <link type="text/css" rel="stylesheet" href="/resources/space.css">
+
+    <link href='/resources/highlighter/styles/shCoreCXF.css' rel='stylesheet' type='text/css' />
+  <link href='/resources/highlighter/styles/shThemeCXF.css' rel='stylesheet' type='text/css' />
+  <script src='/resources/highlighter/scripts/shCore.js' type='text/javascript'></script>
+  <script src='/resources/highlighter/scripts/shBrushJava.js' type='text/javascript'></script>
+  <script src='/resources/highlighter/scripts/shBrushJScript.js' type='text/javascript'></script>
+  <script type="text/javascript">
+  SyntaxHighlighter.defaults['toolbar'] = false;
+  SyntaxHighlighter.all();
+  </script>
+
+  <link href="/styles/style.css" rel="stylesheet" type="text/css"/>
+
+</head>
+<body>
+  <div class="wrapper bs">
+
+<div id="navigation"><div class="nav">
+<ul class="alternate" type="square"><li><a shape="rect" href="index.html" title="Index">Home</a></li><li><a shape="rect" href="getting-started.html" title="Getting Started">Getting Started</a></li><li><a shape="rect" href="documentation.html" title="Documentation">Documentation</a></li><li><a shape="rect" href="download.html" title="Download">Download</a></li><li><a shape="rect" href="about.html" title="About">About</a></li><li><a shape="rect" href="community.html" title="Community">Community</a></li><li><a shape="rect" class="external-link" href="http://www.apache.org/">Apache</a></li><li><a shape="rect" class="external-link" href="http://www.apache.org/foundation/sponsorship.html">Sponsorship</a></li><li><a shape="rect" class="external-link" href="http://www.apache.org/foundation/thanks.html">Thanks</a></li></ul>
+</div></div>
+
+<div id="top">
+<div id="smallbanner"><div class="searchbox" style="float:right;margin: .3em 1em .1em 1em">
+<p>
+<span style="color: #999; font-size: 90%">Tapestry docs, issues, wikis &amp; blogs:</span>
+</p><form enctype="application/x-www-form-urlencoded" method="get" action="http://tapestry.apache.org/search.html">
+  <input type="text" name="q">
+  <input type="submit" value="Search">
+</form>
+
+</div>
+
+<div class="emblem" style="float:left"><a shape="rect" href="index.html" title="Index"><span class="image-wrap" style=""><img src="small-banner.data/tapestry_s.png" style="border: 0px solid black"></span></a></div>
+<div class="title" style="float:left; margin: 0 0 0 3em">
+<h1><a shape="rect" name="SmallBanner-PageTitle"></a>JavaScript Modules</h1></div></div>
+<div class="clearer"></div>
+</div>
+
+<div class="clearer"></div>
+
+  <div id="breadcrumbs">
+        <a href="index.html">Apache Tapestry</a>&nbsp;&gt;&nbsp;<a href="documentation.html">Documentation</a>&nbsp;&gt;&nbsp;<a href="user-guide.html">User Guide</a>&nbsp;&gt;&nbsp;<a href="javascript-modules.html">JavaScript Modules</a>
+    <a class="edit" title="Edit this page (requires approval -- just ask on the mailing list)" href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=41813130">edit</a>
+  </div>
+
+<div id="content">
+<div id="ConfluenceContent"><p>As web applications have evolved, the use of JavaScript in the client has expanded almost exponentially. This has caused all kinds of growing pains, since the original design of the web browser, and the initial design of JavaScript, was never intended for this level of complexity. Unlike Java, JavaScript has no native concept of a "package" or "namespace" and has the undesirable tendency to make everything a global.</p><p>In the earliest days, client-side JavaScript was constructed as libraries that define simple functions and variables:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
+<script class="theme: Default; brush: js; gutter: false" type="syntaxhighlighter"><![CDATA[ 
+function onclickHelp(event) {
+  if (helpModal === undefined) {
+    helpModal = ...
+  }
+  document.getElementById(&quot;modalContainer&quot;) ...
+}
+ 
+$(&quot;#helpButton&quot;).click(onClickHelp);]]></script>
+</div></div><p>What's not apparent here is that function <code>onclickHelp()</code> is actually attached to the global window object. Further, the variable <code>helpModal</code> is also not local, it too gets defined on the window object. If you start to mix and match JavaScript from multiple sources, perhaps various kinds of third-party UI widgets, you start to run the risk of name collisions.</p><p>One approach to solving these kinds of problems is a&#160;<em>hygienic&#160;function wrapper</em>. The concept here is to define a function and immediately execute it. The functions and variables defined inside the function are private to that function.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
+<script class="theme: Default; brush: js; gutter: false" type="syntaxhighlighter"><![CDATA[(function() {
+  var helpModal = null;
+ 
+  function onClickHelp(event) { ... }
+ 
+  $(&quot;#helpButton&quot;).click(onClickHelp);
+})();]]></script>
+</div></div><p>This is an improvement in so far as it assists with name collisions. The variables and functions can only be referenced by name from inside the wrapper.</p><p>However, if you are building a library of code to reuse across your application (or building a library to share between applications) then something is still missing: a way to expose just the function you want from inside you wrapper to the outside world.</p><p>The old-school route is to choose a hopefully unique prefix, building a cumbersome name (perhaps <code>myapp_onClickHelp</code>), and attach that to the global window object. But that just makes your code that much uglier, and leaves you open to problems if not all members of your development team understand the rules and prefixes.</p><p>Enter the <a shape="rect" class="external-link" href="https://github.com/amdjs/amdjs-api/wiki/AMD" >Asynchronous Module Definition</a>. The AMD is pragmatic way to avoid globals, and adds a number of bells and whistles th
 at can themselves be quite important.</p>    <div class="aui-message hint shadowed information-macro">
+                            <span class="aui-icon icon-hint">Icon</span>
+                <div class="message-content">
+                            <p>Tapestry uses the <a shape="rect" class="external-link" href="http://requirejs.org/" >RequireJS</a> library as the client-side implementation of AMD. It supplements this on the server-side with Tapestry services for even more flexibility.</p>
+                    </div>
+    </div>
+<p>Under AMD, JavaScript is broken up into&#160;<em>modules</em>.</p><ul><li>Modules have a unique name, such as <code>t5/core/dom</code> or <code>app/tree-viewer</code>.</li><li>A module has a constructor function that&#160;<em>exports</em> a value.</li><li>A module defines&#160;<em>dependencies</em> on any number of other modules.</li><li>The export of each dependency is provided as a parameter to the constructor function.</li></ul><p>Here's an example from Tapestry itself:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Module t5/core/confirm-click</b></div><div class="codeContent panelContent pdl">
+<script class="theme: Default; brush: js; gutter: false" type="syntaxhighlighter"><![CDATA[(function() {
+  define([&quot;jquery&quot;, &quot;./events&quot;, &quot;./dom&quot;, &quot;bootstrap/modal&quot;], function($, events, dom) {
+    var runDialog;
+    runDialog = function(options) {
+      ...
+    };
+    $(&quot;body&quot;).on(&quot;click&quot;, &quot;[data-confirm-message]:not(.disabled)&quot;, function() {
+      ...
+    });
+    dom.onDocument(&quot;click&quot;, &quot;a[data-confirm-message]:not(.disabled)&quot;, function() {
+      ...
+    });
+    return {
+      runDialog: runDialog
+    };
+  });
+}).call(this);]]></script>
+</div></div>    <div class="aui-message hint shadowed information-macro">
+                            <span class="aui-icon icon-hint">Icon</span>
+                <div class="message-content">
+                            <p>The above code is actually the compiled output of a CoffeeScript source file. The <code><span>confirm-click </span></code>module is used to raise a modal confirmation dialog when certain buttons are clicked; it is loaded by the <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/corelib/mixins/Confirm.html">Confirm</a> mixin.</p>
+                    </div>
+    </div>
+<p>This module depends on several other modules:&#160;<code>jquery</code>, <code>t5/core/events</code>, <code>t5/core/dom</code>, and <code>bootstrap/modal</code>. These other modules will have been loaded, and their constructor functions executed, before the <code>confirm-click</code> constructor function is executed. The export of each module is provided as a parameter in the order in which the dependencies are defined.</p>    <div class="aui-message warning shadowed information-macro">
+                            <span class="aui-icon icon-warning">Icon</span>
+                <div class="message-content">
+                            <p>With AMD, the JavaScript libraries may be loaded in parallel by the browser (that's the <em>asynchronous</em> part of AMD); RequireJS manages the dependency graph and invokes each function just once, as soon as its dependencies are ready, as libraries are loaded. In some cases, a module may be loaded just for its side effects; such modules will be listed last in the dependency array, and will not have a corresponding parameter in the dependent module's constructor function. In <code>confirm-click</code>, the <code>bootstrap/modal</code> module is loaded for side-effects.</p>
+                    </div>
+    </div>
+<p><code>confirm-click</code> defines a local function, <code>runDialog</code>. It performs some side-effects, attaching event handlers to the body and the document. It's export is a JavaScript object containing a function that allows other modules to raise the modal dialog.</p><p>If a module truly exports only a single function and is unlikely to change, then it is acceptable to just return the function itself, not an object containing the function. However, returning an object makes it easier to expand the responsibilities of <code>confirm-click</code> in the future; perhaps to add a <code>dismissDialog</code> function.</p><h3 id="JavaScriptModules-LocationofModules">Location of Modules</h3><p>Modules are stored as a special kind of Tapestry <a shape="rect" href="assets.html">asset</a>. On the server, modules are stored on the class path under <code>META-INF/modules</code>. In a typical environment, that means the sources will be in <code>src/main/resources/META-INF/modules</code>
 .</p><p>Typically, your application will place it's modules directly in this folder. If you are writing a reusable library, you will put modules for that library into a subfolder to prevent naming conflicts. Tapestry's own modules are prefixed with <code>t5/core</code>.</p><p>If you are using the optional&#160;<code>tapestry-web-resources</code> module (that's a server-side module, not an AMD module), then you can write your modules as CoffeeScript files; Tapestry will take care of compiling them to JavaScript as necessary.</p><p>The service <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/services/javascript/ModuleManager.html">ModuleManager</a> is the central piece of server-side support for modules. It supports&#160;<em>overriding</em> of existing modules by contributing overriding <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/services/javascript/JavaScriptModuleConfig
 uration.html">module definitions</a>. This can be useful to <a shape="rect" class="external-link" href="http://en.wikipedia.org/wiki/Monkey_patch" >monkey patch</a> an existing module supplied with Tapestry, or as part of a third-party library.</p><h3 id="JavaScriptModules-LoadingModulesfromTapestryCode">Loading Modules from Tapestry Code</h3><p>Often, you will have a Tapestry page or component that defines client-side behavior; such a component will need to load a module.</p><p>The simplest approach is to use the <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/annotations/Import.html">Import</a> annotation:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
+<script class="theme: Default; brush: java; gutter: false" type="syntaxhighlighter"><![CDATA[@Import(module = &quot;t5/core/confirm-click&quot;)
+public class Confirm
+{
+  ...
+}]]></script>
+</div></div><p>The <code>module</code> attribute may either a single module name, or a list of module names.</p><p>In many cases, you not only want to require the module, but invoke a function exported by the module. In that case you must use the <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/services/javascript/JavaScriptSupport.html">JavaScriptSupport</a> environmental.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
+<script class="theme: Default; brush: java; gutter: false" type="syntaxhighlighter"><![CDATA[  @Environmental
+  JavaScriptSupport javaScriptSupport;
+ 
+  ...
+ 
+  javaScriptSupport.require(&quot;my-module&quot;).with(clientId, actionUrl);
+ 
+  ...
+ 
+  javaScriptSupport.require(&quot;my-module&quot;).invoke(&quot;setup&quot;).with(clientId, actionUrl);]]></script>
+</div></div><p>In the first example, <code>my-module</code> exports a single function of two parameters. In the second example, <code>my-module</code> exports an object and the <code>setup</code> key is the function that is invoked.</p><h3 id="JavaScriptModules-DevelopmentMode">Development Mode</h3><p>In development mode, Tapestry will write details into the client-side console.</p><p><img class="confluence-embedded-image" src="https://cwiki.apache.org/confluence/download/attachments/41813130/Tapestry_Integration_Test_Application_and_JavaScriptSupport__Tapestry_API_Documentation_.png?version=1&amp;modificationDate=1401727827255&amp;api=v2" data-image-src="/confluence/download/attachments/41813130/Tapestry_Integration_Test_Application_and_JavaScriptSupport__Tapestry_API_Documentation_.png?version=1&amp;modificationDate=1401727827255&amp;api=v2"></p><p>This lists modules&#160;<em>explicitly</em> loaded (for initialization), but does not include modules loaded only as dependencies. You
  can see more details about what was actually loaded using&#160;<em>view source</em>; RequireJS adds <code>&lt;script&gt;</code> tags to the document to load libraries and modules.</p><h3 id="JavaScriptModules-Librariesvs.Modules">Libraries vs. Modules</h3><p>Tapestry still supports JavaScript libraries. &#160;When the page is loading, all libraries are loaded before any modules.</p><p>Libraries are loaded sequentially, so if you can avoid using libraries, so much the better in terms of page load time.</p><p>Libraries work in both normal page rendering, and Ajax partial page updates. Even in partial page updates, the libraries will be loaded sequentially before modules are loaded or exported functions invoked.</p><h3 id="JavaScriptModules-AggregatingModules">Aggregating Modules</h3><p>An important part of performance for production applications is JavaScript aggregation.</p><p>In development mode, you want your modules and other assets to load individually. Unlike assets, modules ca
 n't be fingerprinted, so on each page load, the client browser must ask the server for the module again (typically getting a 304 Not Modified response).</p><p>This is acceptable in development mode, but quite undesirable in production.</p><p>With JavaScript aggregation, the module can be included in the single virtual JavaScript library that represents a <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/services/javascript/JavaScriptStack.html">JavaScript stack</a>. This significantly cuts down on both the number of requests from the client to the server, and the overall number of bytes transferred.</p><p>Adding a module to the stack is not the same as <code>require</code>-ing it. In fact, you must still use <code>JavaScriptSupport.require()</code> regardless.</p><p>What adding a module to a stack accomplishes is that the module's code is downloaded in the first, initial JavaScript download. When (and if) the module is required a
 s a dependency, the code will already be present in the browser and ready to execute.</p><p>Tapestry&#160;<strong>does not</strong> attempt to do dependency analysis; that is left as a manual exercise. Typically, if you aggregate a module, your should look at its dependencies, and aggregate those. Failure to do so will cause unwanted requests back to the Tapestry server for the dependency modules, even though the aggregated module's code is present.</p><p>Because Tapestry is open, it is possible to contribute modules even into the&#160;<strong>core</strong> JavaScript stack. &#160;This is done using your application's module:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
+<script class="theme: Default; brush: java; gutter: false" type="syntaxhighlighter"><![CDATA[    @Contribute(JavaScriptStack.class)
+    @Core
+    public static void addAppModules(OrderedConfiguration&lt;StackExtension&gt; configuration) {
+        configuration.add(&quot;tree-viewer&quot;, StackExtension.module(&quot;tree-viewer&quot;));
+		configuration.add(&quot;app-utils&quot;, StackExtension.module(&quot;app-utils&quot;));
+    }]]></script>
+</div></div><p>To break this down:</p><ul><li>@Contribute indicates we are contributing to a JavaScriptStack service</li><li>Since there are (or at least, could be) multiple services that implement JavaScriptStack, we provide the&#160;@Core annotation to indicate which one we are contributing to</li><li>It is possible to contribute libraries, CSS files, other stacks, and modules; here we are contributing modules</li><li>Each contribution has a unique id and a <a shape="rect" class="external-link" href="http://tapestry.apache.org/5.4/apidocs/org/apache/tapestry5/services/javascript/StackExtension.html">StackExtension</a> value</li></ul><p>The core stack includes several libraries and modules; the exact configuration is subject to a number of factors (such as whether Prototype or Scripaculous is the used as the underlying framework). That being said, this is the&#160;<em>current</em> list of modules aggregated into the core stack:</p><ul><li>jquery</li><li>underscore</li><li>t5/core/<
 ul><li>alert</li><li>ajax</li><li>bootstrap</li><li>console</li><li>dom</li><li>events</li><li>exception-frame</li><li>fields</li><li>pageinit</li><li>messages</li><li>util</li><li>validation</li></ul></li></ul></div>
+</div>
+
+<div class="clearer"></div>
+<div id="footer">
+<div id="footer"><p>Apache Tapestry, Tapestry, Apache, the Apache feather logo, and the Apache Tapestry project logo are trademarks of The Apache Software Foundation.<br clear="none">
+</p><p><script type="text/javascript">
+  var _gaq = _gaq || [];
+  _gaq.push(['_setAccount', 'UA-400821-1']);
+  _gaq.push(['_trackPageview']);
+
+  (function() {
+    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+  })();
+</script></p><p></p></div>
+</div>
+		<div id="comments_thread"></div>
+		<script type="text/javascript" src="https://comments.apache.org/show_comments.lua?site=tapestry&amp;page=http://tapestry.apache.org/javascript-modules.html" async="true">
+		</script>
+		<noscript>
+		<iframe width="100%" height="500" src="https://comments.apache.org/iframe.lua?site=tapestry&amp;page=http://tapestry.apache.org/javascript-modules.html"></iframe>
+		</noscript>
+  </div>
+</body>
+</html>