際際滷

際際滷Share a Scribd company logo
Javascript & Templates Ideas to Inspire Better Coding
Overview Javascript Objects  Prototype statement  Event delegation Examples JSON Javascript templates Putting it all together Questions Suggestions
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.
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
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;
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 }
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 ... */};
Associative Arrays (contd) var mailbox = {0: &quot; mail number 1)&quot;, 1: &quot;(mail number 2)&quot;, 2: &quot;(mail number 3)&quot;}; 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(&quot;Processing&quot; + ind + &quot;: &quot; + mailbox[ind]); This does not work: for (var ind = 0; ind <= mailbox.length; ind++) //. length  attribute is not defined for Object
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(); };
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!
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; }
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 objects abilities (AJAX, DOM Manipulation, event delegation, etc)
Questions?
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=/slideshow/javascripttemplating/1466488/ onclick=doSomething()/>
Handler functions can be passed the event object <img src=/slideshow/javascripttemplating/1466488/ 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 }
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 its 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=${}/>
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; }
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); 油  } }
Sample Code #1 Example 1: validations.js validate_old.html View in Browser  NOTE: If the event Handler changes its name, it is going to be tedious to find and change all references in the application.
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
Questions?
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/
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 Im poking around with to see if its worth using in house.
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
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; } ]
Note that JSON format doesnt natively follow a definition of its 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 }
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> 油油 油 ] }
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 dont accept the application/json MIME type, but its 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.
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 += /slideshow/javascripttemplating/1466488/; Templates
Questions?
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=/slideshow/javascripttemplating/1466488/> are some examples in JSP  Template support can be written in Javascript, and it already has
Why use Javascript templates? Cacheable!  If you need JavaScript code to generate a lot of HTML (or even new JavaScript), youre 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=/slideshow/javascripttemplating/1466488/&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;/>
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 shouldnt 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)
Using template.js  Dont, 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=/slideshow/javascripttemplating/1466488/ style=display:none> containing the pattern var s = TrimPath.processDOMTemplate(templateId, jsonDataObj); var l = document.getElementById(IdOfWriteLocation); if(l){ 油油 l.innerHTML = s; }
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, its a powerful JS library with an unfortunately confusing name)
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));
Example: Javascript template  Javascript template example:  customerPrefDetails.jst Documentation   for template.js
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')); }
Questions?
Suggestions How could I have made this better? Was it easy to understand? What would you like to learn more about?   less about?

More Related Content

What's hot (20)

javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
Javascript
JavascriptJavascript
Javascript
mussawir20
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
Sasidhar Kothuru
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
Javascript
JavascriptJavascript
Javascript
theacadian
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
Walid Ashraf
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
Java script
Java scriptJava script
Java script
Shyam Khant
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
Walid Ashraf
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath

Similar to Javascript Templating (20)

eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
borkweb
Java script
Java scriptJava script
Java script
Adrian Caetano
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS Framework
Mohd Imran
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
dominion
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
Roberto Suggi Liverani
JS basics
JS basicsJS basics
JS basics
Mohd Saeed
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
C5 Javascript
C5 JavascriptC5 Javascript
C5 Javascript
Vlad Posea
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
Wildan Maulana
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
Ramamohan Chokkam
Json
JsonJson
Json
mussawir20
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
Refresh Events
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
Eugene Andruszczenko
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j query
Tricode (part of Dept)
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Zohar Arad
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
borkweb
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb
Introduction to Prototype JS Framework
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS Framework
Mohd Imran
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
dominion
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
C5 Javascript
C5 JavascriptC5 Javascript
C5 Javascript
Vlad Posea
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
Wildan Maulana
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
Ramamohan Chokkam
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
Refresh Events
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
Eugene Andruszczenko
Zend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j queryZend framework 05 - ajax, json and j query
Zend framework 05 - ajax, json and j query
Tricode (part of Dept)
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Zohar Arad

Javascript Templating

  • 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&quot;: &quot;Dear nephew, ...&quot;, &quot;the second e-mail&quot;: Blah..., /* and so on ... */};
  • 8. Associative Arrays (contd) var mailbox = {0: &quot; mail number 1)&quot;, 1: &quot;(mail number 2)&quot;, 2: &quot;(mail number 3)&quot;}; 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(&quot;Processing&quot; + ind + &quot;: &quot; + 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 objects abilities (AJAX, DOM Manipulation, event delegation, etc)
  • 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=/slideshow/javascripttemplating/1466488/ onclick=doSomething()/>
  • 15. Handler functions can be passed the event object <img src=/slideshow/javascripttemplating/1466488/ 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 its 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 its 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
  • 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 Im poking around with to see if its 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 doesnt natively follow a definition of its 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 dont accept the application/json MIME type, but its 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 += /slideshow/javascripttemplating/1466488/; Templates
  • 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=/slideshow/javascripttemplating/1466488/> 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), youre 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=/slideshow/javascripttemplating/1466488/&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 shouldnt 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 Dont, 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=/slideshow/javascripttemplating/1466488/ 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, its 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')); }
  • 40. Suggestions How could I have made this better? Was it easy to understand? What would you like to learn more about? less about?