Javascript advanced tutorial

Quick JS Background

Usages
  

Why web developers need to know JS
 

Browser Server-side – ASP Java, C++

Libraries
   

Any website owner wants JS effects MVC libraries do less and less more (http:// raibledesigns.com/rd/entry/do_we_even_need_web)
Prototype – excellent for high traffic websites Ext js – excellent for Administration interfaces Dojo – excellent features – unfortunately bad UI – blocks the adoption DWR – excellent RPC library

JS Usage Tips&Tricks

Code

  

Code conventions (inspired from Dojo code conventions)

   

Usage
    

Any utility function has already been written 20 times (prototype, ext, dojo) Keep the code clean and decoupled Use unit tests whenever possible – small HTML pages for testing various JS scripts Avoid global scope. Declare your variables in local scopes. Always test with two browsers FF and IE Firebug rulz - YSlow is a good indicator for improving page performances Microsoft IE Developer Toolbar & Microsoft Script Debugger For large websites – DWR & Prototype – small load time, very useful functions, easy to call, large user base Ajax – next time

Class names – UpperLower, methods – upperLower Private methods - _methodName Do not use reserved keywords! Ex: function or action. Never use an input named “action” in a form

Javascript Language
1.

Variables scope
var x = 2; y = 3;

2.

Objects

Example 1: declare classes
<HTML><HEAD><SCRIPT>

function Dog(name, age) { this.name = name; this.age = age; } Dog.prototype.bark = function() { alert("Ham ham, ma numesc:" + this.name + ", si am " + this.age + " ani"); } var azorel = new Dog("Azorel", 2); azorel.bark(); alert(azorel["name"]); azorel["bark"]();
</SCRIPT></HEAD></HTML>

Example 2: enrich existing objects
<HTML><HEAD><SCRIPT>

String.prototype.trim = function() {return this.replace(/^\s+/, '').replace(/\s+$/, '');} alert("aa bb ".trim().length)
</SCRIPT></HEAD></HTML>

Javascript Language (continued)
3.

Language
   

4.

objectIsNull() – utility function for verifying the validity of an object
objectIsNull = function(obj) { return !(!obj || obj == null || typeof(obj) == "undefined"); } var x = 10; var o = { x: 15 };

CAREFUL with ; try { cod; } catch(e) {alert("A aparut o eroare! " + e);} Retrieve a number from a string using: parseInt, parseFloat, Number("string") Obiect declaration: var dog = { age: 3, name: "Azorel", bark: function() { alert("Ham ham, ma numesc:" + this.name + ", si am " + this.age + " ani"); } dog.bark();

5.

apply method – method for the Function object (along with toString/call)
function f() { alert(this.x); } f(); f.call(o); // equivalent for o.f()

Javascript Language (continued)
6. 7. 8. arguments property
function() { alert(arguments.length); }

DWR.toDescriptiveString(object, level) – an excellent utility function for debugging the contents of an object Regular expressions
  

9.

AOP in Javascript
 

var pattern = /s$/; - everything ending with s text.replace(/javascript/gi, "JavaScript"); - replaces all appearances (g) of “javascript” string in a case insensitive (i) with “JavaScript” string "1 plus 2 equals 3".match(/\d+/g) – returns ["1", "2", "3"]

Dojo

dojo.event.connect – Dojo’s internal glue - dojo.event.connect(object, "methodName", function() {});

Prototype

Event.observe("elementId", "click", function(event){ alert("clicked!");}); Event.observe(document, "keypress", function(event){ if(event.keyCode == Event.KEY_RETURN) alert("Enter Pressed");}); Event.observe(document, "mousemove", function(event){$("mouse").value = "X: " + Event.pointerX(event) + "px Y: " + Event.pointerY(event) + "px";});

Javascript Language (continued)
10. Custom AOP
<HTML><HEAD><SCRIPT> function Dog(name, age) { this.name = name; this.age = age; } Dog.prototype.bark = function() { alert("Ham ham, ma numesc:" + this.name + ", si am " + this.age + " ani"); } var addAfter = function(obj, methodName, after) { var orig = obj[methodName]; obj[methodName] = function() { orig.apply(this, arguments); return after(arguments); } } var azorel = new Dog("Azorel", 2); addAfter( azorel, "bark", function(){alert(" si o sa va mananc pe toti... muhaha");}); azorel.bark(); </SCRIPT></HEAD></HTML> Why is orig available when calling azorel.bark()? The answer lies in the “lexically” scoped functions in Javascript (as opposed to a runtime scope). When you define a nested function, however, the scope chain includes the containing function. This means that nested functions can access all of the arguments and local variables of the containing function.

Javascript Language (continued)
11. Java usage (JDK1.6 only)
public class test { public static void main(String[] args) throws IOException { ScriptEngineManager scriptManager = new ScriptEngineManager(); ScriptEngine js = scriptManager.getEngineByExtension("js"); Bindings bindings = js.createBindings(); bindings.put("globalStr", "mama mia"); try { Object o = js.eval("function trim(str) {return str.replace(/^\\s+/, '').replace(/\\s+$/, '');} trim(globalStr);", bindings); System.out.println(o); } catch (ScriptException ex) { System.out.println(ex); } } }

Resources
JavaScript: The Definitive Guide, 5th Edition http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/ http://dojotoolkit.org http://www.prototypejs.org/

End

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.