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 (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
Object Definition var mailbox = {0: " mail number 1)", 1: "(mail number 2)", 2: "(mail number 3)"}; 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("The date to format:"+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 object’s 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=“…” onclick=“doSomething(…)”/>
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.
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 "userID"
}
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 //"onChange" attributes calling an updated function name var evt = e ? e : window.event; var oElem = oForm[this.name]; if(oElem && oElem.getAttribute("validate")) { //test for null var value = oElem.value; //automatically update the dirty flag oElem.dirty = (value != oElem.originalValue); if("phone" == oElem.getAttribute("validate")) validatePhone(value); else if("email" == oElem.getAttribute("validate")) validateEmail(value); } }
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.
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 I’m poking around with to see if it’s worth using in house.
JSON Format
"Image": { "Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "/image/481989943",
"Height": 125,
"Width": "100“
},
"IDs": [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.
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.
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
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=“…”> 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), you’re probably familiar with seeing more complex variations of escaped code, than my example below:
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)
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;
}
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)
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.
This was a presentation I wrote for a previous empl more
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. less
0 comments
Post a comment