Your SlideShare is downloading. ×
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Javascript Templating
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Javascript Templating

987

Published on

This was a presentation I wrote for a previous employer, aimed at Java developers. The goal was to help them understand some of the new UI conventions I was putting into their application, so that …

This was a presentation I wrote for a previous employer, aimed at Java developers. The goal was to help them understand some of the new UI conventions I was putting into their application, so that they would be able to develop "smarter" JSP code.

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
987
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Javascript & Templates Ideas to Inspire Better Coding
  • 2. Overview
      • Javascript Objects
      • Prototype statement
      • Event delegation
      • Examples
      • JSON
      • Javascript templates
      • Putting it all together
      • Questions
      • Suggestions
  • 3. First, a good JavaScript site
      • Want to become a better JavaScript developer? Here is a good link, filled with all sorts of good understanding of how to write better code.
  • 4. Javascript Objects
      • Object types:
        • Object
        • Date
        • Array
        • Function
        • Event
      • New instances of Object types created using:
    • var w = new Object(); //can contain anything
    • var x = new Date(); //value = today date AND time
    • var y = new Array(…); //index values can be specified
    • var z = new Function(…) {…} //objects can be passed in, function accessed like a variable (ie, no “()” after ‘y’
  • 5. Primitive Types
      • Primitive Types:
        • undefined
        • number
        • string
      • New instances of Primitive types created using:
    • var w = 5; //number
    • var x; //undefined
    • var y = “3”; //string
    • var z = 4; //number
      • Primitive types allow you to do silly things:
    • w+z+y = “93”;
    • w+y+z = “534”;
    • x+w = NaN; //Not a Number (isNan() can test these)
    • isNan(y) = false; //string looks like number (quirk)
    • isNan(x) = true;
  • 6. Determining Object Type
      • typeof is a statement you can use to determine which type of Object a variable is.
    • var x = new Date();
    • alert(typeof(x)); //displays “Date”
      • This method is useful to determine if functions exist, variables are defined, etc.
    • if(“function” == typeof(doSomething)) {
    •      doSomething();
    • }else if(“undefined” = typeof(doSomething)) {
    •      //alert user, insert js library, etc
    • }
  • 7. Associative Arrays
      • Associative Arrays are like HashMaps in Java.
      • They are typeof Object , not Array
      • Useful for keying data by Objects, rather than index.
    • var mailArchive = {“msgID_43": "Dear nephew, ...",
    • "the second e-mail": “Blah...“,
    • /* and so on ... */};
  • 8. Associative Arrays (cont’d)
    • var mailbox = {0: " mail number 1)",
    • 1: "(mail number 2)",
    • 2: "(mail number 3)"};
      • Note that Associative arrays are objects, so the values you put in them need to be name:value and followed by a comma (except for last one)
      • To iterate:
    • for (ind in mailbox)
    • alert("Processing" + ind + ": " + mailbox[ind]);
      • This does not work:
    • for (var ind = 0; ind <= mailbox.length; ind++)
    • //. length attribute is not defined for Object
  • 9. Object Definition var mailbox = {0: &quot; mail number 1)&quot;, 1: &quot;(mail number 2)&quot;, 2: &quot;(mail number 3)&quot;}; OR, create your own object type : function FormObject(id) {      var obj = oForm[id];      obj.originalValue = obj.value;      obj.dirty = false;      obj.onchange = doSomething(); };
  • 10. prototype statement
      • The prototype statement allows you to extend the functionality of an object.
        • Custom variables
        • Custom methods
        • Custom events
      • Think of a prototyped object like any Java Object that extends another Object.
      • Do not add prototypes to the global scope for native Javascript objects. Create your own object type!
  • 11. Extending Objects Date.prototype.format = function(vFormat) {     //'this' is just like in Java      alert(&quot;The date to format:&quot;+this);     var x = (//...do date formatting w/ ‘this’ & ‘vFormat’);     return x; }
  • 12. Practical use of prototype
      • Overwriting browser specific methods to make the cross-browser
        • window.showModalDialog (IE only)
        • window.prototype.showModalDialog can be coded to do a browser test and use IE implementation, and use custom code in Firefox.
      • Adding useful methods to objects
      • Abstraction of functionality
      • Limiting scope of variables not used by other code
      • Building powerful custom object types
      • Anything that JavaScript can do, can be written into an object’s abilities (AJAX, DOM Manipulation, event delegation, etc)
  • 13. Questions?
  • 14. Event Delegation
      • Events are fired when certain events occur in the browser. They can be captured with “Event Handlers”:
        • onload : when the HTML code has been parsed and displayed by browser
        • onchange : when the value of a form object changes
        • onsubmit : when the form is submitted. (return false, if you want to stop the form submit)
        • onclick : when an page element is clicked on.
        • More…
      • Event Handlers call JavaScript code, not necessarily functions.
    • <img src=“…” onclick=“doSomething(…)”/>
  • 15.
      • Handler functions can be passed the event object
    • <img src=“…” onclick=“doSomething( event )”/>
      • The event object is most useful for finding:
        • The DOM object that triggered the event
        • The type of event that occurred
      • getTargetElement finds the object the event was triggered by (i.e., an input that changed, button clicked, etc.). Once we have the element, we can traverse the DOM.
    • function getTargetElement(evt) {
    •     evt = (evt)? evt: ((window.event) ? window.event : &quot;&quot;);
    •      var elem;
    •     if (evt.target) {
    •          elem = (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;
    •      } else {
    •      elem = evt.srcElement;
    •     }
    •     return elem;
    • }
    • function doSomething(evt) {
    •     var oElem = getTargetElement(evt);
    •      //oElem.parentNode, oElem.innerHTML, oElem.getAttribute(…), etc
    • }
  • 16. DOM (Document Object Model)
      • The DOM is the structure of the HTML document (or XML document).
      • It follows a data type definition (DTD) of strict, loose, transitional, defined by a <meta> tag.
      • You can adhere to the DOM DTD, but because it’s structure is understood, you can start adding attributes to elements.
    • <table id=“resources” onclick=“editTechnician(event)”>
    •   <tr PK=“335abc”><td>Bob Smith</td></tr>
    •   <tr PK=“3fe2452”><td>Sally Jones</td></tr>
    •   <tr PK=“abe325”><td>Marky Mark</td></tr>
    • </table>
    • <input name=“blah” isDirty=“false” origValue=“${…}” value=“${…}”/>
  • 17. Events and DOM
      • Using the event capturing method, we can use the structured data that the DOM presents us to:
        • Reduce the need to ‘re-request’ data
        • Remove JavaScript objects containing info already in the DOM (another reason why custom attributes are encouraged, more data available).
        • Reduce JavaScript code & function calls
    • function editTechnician(evt) { //user clicked “Bob Smith”
    •   var oElem = getTargetElement(evt); //TD or TR
    •   var oTR = getRow(oElem); //ensures we have the TR elem
    •   var userId = oTR.getAttribute(“PK”); //get PK attribute
    •   //do something with &quot;userID&quot;
    • }
  • 18. Custom Objects, Events and prototype function FormObject(id) { //constructor pattern   //set properties to the form element's DOM object dynamically   var obj = oForm[id];     obj.originalValue = obj.value; //original value preserved   obj.dirty = false; //has object value changed?     //register an onchange to each input needing validation   obj.onchange = this.validate; } //assign validation function to FormObject's FormObject.prototype.validate = function(e) { //by doing it this way, you don't have to change any occurrence of //&quot;onChange&quot; attributes calling an updated function name var evt = e ? e : window.event; var oElem = oForm[this.name]; if(oElem && oElem.getAttribute(&quot;validate&quot;)) { //test for null   var value = oElem.value;   //automatically update the dirty flag   oElem.dirty = (value != oElem.originalValue);   if(&quot;phone&quot; == oElem.getAttribute(&quot;validate&quot;))     validatePhone(value);   else if(&quot;email&quot; == oElem.getAttribute(&quot;validate&quot;))     validateEmail(value);   } }
  • 19. Sample Code #1
      • Example 1:
        • validations.js
        • validate_old.html
      • View in Browser
      • NOTE: If the event Handler changes it’s name, it is going to be tedious to find and change all references in the application.
  • 20. Sample Code #2 & 3
      • Example 2:
        • validations.js
        • FormObject.js (NOTE: object js files are Capitalized)
        • validate.html
      • Example 3:
        • validations.js
        • FormObject.js
        • validate_best.html
      • View in Browser
        • (Demonstrate how easy it is to change validate in source)
        • NOTE: Auto-Validation occurs as a behavior of FormObject objects
  • 21. Questions?
  • 22. JSON (pronounced Jason)
      • JSON === JavaScript Object Notation
      • A JSON object is just a Javascript Object that follows a very specific and SIMPLE format.
      • There is an RFC that exists for it.
        • An “Request For Comments” (RFC) is a document that is working notes of the Internet Research and Development Community.
        • An RFC document may be on essentially any topic related to computer communication, and may be anything from a meeting report to the specification of a protocol standard.
      • JSON documented on the net:
        • http://www.json.org/
  • 23. JSON Objects
      • JSON objects can be assembled by ANY language, but only useful when passed to Javascript at some point.
      • Some servers and servlets are already allowing the Java code the option to return data in JSON format.
        • Struts 2 can do this
        • DWR returns a JavaScript object that can be easily transformed into a JSON object.
        • There is a JSON tag-library that I’m poking around with to see if it’s worth using in house.
  • 24. JSON Format
    • &quot;Image&quot;: { &quot;Width&quot;: 800,
    •      &quot;Height&quot;: 600,
    •      &quot;Title&quot;: &quot;View from 15th Floor&quot;,
    •      &quot;Thumbnail&quot;: {
    •          &quot;Url&quot;: &quot;/image/481989943&quot;,
    •            &quot;Height&quot;: 125,
    •                  &quot;Width&quot;: &quot;100“
    •      },
    •      &quot;IDs&quot;: [116, 943, 234, 38793]
    • }
      • Note that JSON objects have a simple and rich structure. It is possible to convert structured objects (Java, XML, other) into JSON objects with the appropriate compiler or tools.
        • JSON taglib
        • JSON for Java
  • 25.
      • This is a JSON array containing two objects:
    • [
    •   { &quot;precision&quot;: &quot;zip&quot;,
    •      &quot;Latitude&quot;: 37.7668,
    •      &quot;Longitude&quot;: -122.3959,
    •      &quot;Address&quot;: &quot;&quot;,
    •      &quot;City&quot;: &quot;SAN FRANCISCO&quot;,
    •      &quot;State&quot;: &quot;CA&quot;,
    •      &quot;Zip&quot;: &quot;94107&quot;,
    •      &quot;Country&quot;: &quot;US&quot;}, //Note: comma delimited objects
    •   { &quot;precision&quot;: &quot;zip&quot;,
    •      &quot;Latitude&quot;: 37.371991,
    •      &quot;Longitude&quot;: -122.026020,
    •      &quot;Address&quot;: &quot;&quot;,
    •      &quot;City&quot;: &quot;SUNNYVALE&quot;,
    •      &quot;State&quot;: &quot;CA&quot;,
    •      &quot;Zip&quot;: &quot;94085&quot;,
    •      &quot;Country&quot;: &quot;US&quot; }
    • ]
  • 26.
      • Note that JSON format doesn’t natively follow a definition of it’s structure
    • var tech = {
    •     “ name” : “Brian Ruhl”,
    •     “ branchId” : “abc_pest_4322”,
    •     “ jobs” : [
    •          { “address” : “...”,
    •           “ time” : “15:30”,
    •           “ num_of_services” : 32
    •          },
    •          { “address” : “...”,
    •           “ time” : “17:30”,
    •           “ num_of_services” : 3,
    •            “ required” : true //Allowed, but sloppy
    •          }
    •      ],
    •     “ techId” : “352a3bd”
    • }
  • 27. JSON in JSP <%@ taglib uri=&quot;/WEB-INF/c.tld&quot; prefix=&quot;c&quot;%> {       &quot;name&quot; : &quot;${initData.name}&quot;,      &quot;address&quot; : &quot;${initData.address}&quot;,      &quot;phone&quot; : &quot;${initData.phone}&quot;,      &quot;serviceType&quot; : &quot;${initData.serviceType}&quot;,      &quot;serviceLength&quot; : ${initData.serviceLength},      &quot;prefTechs&quot; : [      <c:if test=&quot;${not empty initData.prefTechs}&quot;>          <c:forEach var=&quot;tech&quot; items=&quot;${initData.prefTechs}&quot;                      varStatus=&quot;status&quot;>        {          &quot;name&quot; : &quot;${tech.first}&quot;,          &quot;techId&quot; : &quot;${tech.second}&quot;        }<c:if test=&quot;${!status.last}&quot;>,</c:if>          </c:forEach>      </c:if>      ] }
  • 28. AJAX & JSON
      • JSON can be generated by Java, JSP, taglibrary.
      • Responding to AJAX requests with JSON offers structured data that Javascript natively understands.
      • Currently, browsers don’t accept the “application/json” MIME type, but it’s ok to return it as “text/plain”.
      • When requesting JSON data via AJAX, the responseText must be evaluated:
    • var j = eval('(' + XHRObj.responseText + ')');
      • The '{' operator is subject to a syntactic ambiguity in JavaScript: it can begin a block or an object literal. We wrap the text in parenthesis to eliminate the ambiguity.
  • 29. DWR and JSON
      • DWR defines how to convert Java objects into Javascript objects. These Javascript objects are in JSON format.
      • DWR “function call” makes AJAX request and response is returned as JSON object.
      • Data can be displayed two ways:
        • oElem.innerHTML += “…”;
        • Templates
  • 30. Questions?
  • 31. Templates
      • Templates make code:
        • Reusable
        • Maintainable
        • Easier to read and test
          • Test scripts testing code in a fragment can be reused by other scripts
      • Tiles, <jsp:include>, <@page file=“…”> are some examples in JSP
      • Template support can be written in Javascript, and it already has…
  • 32. Why use Javascript templates?
      • Cacheable!
      • If you need JavaScript code to generate a lot of HTML (or even new JavaScript), you’re probably familiar with seeing more complex variations of escaped code, than my example below:
    • '<a onclick=&quot;skillDeleteRows('+array[0]+');&quot; style=&quot;cursor: pointer&quot;><img src=&quot;/images/button_trash.gif“ alt=&quot;Remove&quot;/></a>'+'<input type=&quot;hidden&quot; name=&quot;skillIds&quot; value=&quot;'+array[0]+'&quot;/>';
      • By using a template, you can make this code look more like code (no escaping, no “+” stuff, etc):
    • <a onclick=&quot;skillDeleteRows(${data.id});&quot; style=&quot;cursor:pointer;&quot;>
    •   <img src=&quot;/images/button_trash.gif&quot; alt=&quot;Remove&quot;/>
    • </a>
    • <input type=&quot;hidden&quot; name=&quot;skillIds&quot; value=&quot;${data.id}&quot;/>
  • 33. template.js library
      • A library that allows you to format HTML code into a syntax VERY close to JSTL
      • Documentation
      • Code can be reusable, but implementation requires you to put template fragment inside of a <textarea> ( dumb )
        • Dumb : We now have these <textarea>s that are submitted by the form that shouldn’t be
        • The reason for putting this in a <textarea> was so that the template could be extracted without risking modification by parsing (ie, Javascript)
        • Dumb : Once the pattern is parsed and the data object is compiled through it, we get a HTML string, which 99% of the time we want to write to an element on the page. However, to do the ‘write’ to the page, we need to write another line to do the innerHTML write.
        • Able to access other Javascript objects (functions, variables, etc)
  • 34. Using template.js
      • Don’t, unless you need to parse the generated HTML string one more time...for some reason.
      • Requires:
        • JSON data object
        • template.js included on page
        • <textarea id=“…” style=“display:none”> containing the pattern
    • var s = TrimPath.processDOMTemplate(templateId, jsonDataObj);
    • var l = document.getElementById(IdOfWriteLocation);
    • if(l){
    •    l.innerHTML = s;
    • }
  • 35. exttemplate.js
      • Extends template.js parser objects
      • Retrieves template pattern file via AJAX
      • Able to access other Javascript objects (functions, variables, etc)
      • Resources required
        • template.js
        • exttemplate.js
        • prototype.js (NOTE: This should not be confused with the prototype statement, it’s a powerful JS library with an unfortunately confusing name)
  • 36. Using exttemplate.js
      • Template data patterns follow those of template.js
      • Method call requires:
        • JSON data object
        • JST template file location
        • ID of HTML element to write compiled template source into
      • We name the template files with an extension of .jst (JavaScript Template), to distinguish them from JSPs and other fragments.
    • TrimPath.processTemplateFile('/<filepath>.jst', jsonObj,             document.getElementById(idOfWriteLocation));
  • 37. Example: Javascript template
      • Javascript template example: customerPrefDetails.jst
      • Documentation for template.js
  • 38. Putting it all Together
      • Currently, the “Preferred Technician” Map is using DWR, JSON, and Javascript Templates .
    • /**
    • * onClick event for a dot, gets the customer preference
    • * data from DWR
    • */
    • function getCustomerDetails(customerId) {
    •      $('customerDetails').update();
    •      PrefTechDWR.getCustomerDetails(customerId,
    •      {callback:function(xferObj) {
    •          displayCustomerData(xferObj)},
    •          errorHandler:function(str){
    •              alert(&quot;there was an issue with the server:&quot;+str)},
    •          asynch:false
    •      });
    • }
    • /**
    • * Given a customer object, draw the data using trimpath
    • * into the page.
    • */
    • function displayCustomerData(customer) {
    •      var oObj = {customer:customer};
    •      TrimPath.processTemplateFile('/configuration/customerPrefDetails.jst',
    •          oObj, $('customerDetails'));
    • }
  • 39. Questions?
  • 40. Suggestions
      • How could I have made this better?
      • Was it easy to understand?
      • What would you like to learn more about?
      • … less about?

×