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.
JavaScript is an object-based scripting language used to add interactivity to web pages in browsers by manipulating HTML objects and handling events. It was originally developed at Netscape to enable dynamic and interactive pages but is now supported by all major browsers. The document provides an overview of JavaScript objects, events, and how to get started using it with HTML.
JavaScript is a scripting language originally designed for web browsers but now used everywhere. It has dynamic typing and supports object-oriented, imperative, and functional programming. JavaScript was created in 1995 and standardized in 1999. It is now the most popular language on GitHub. JavaScript can be used to build interactive web pages, desktop applications, server-side applications, IoT applications, and real-time applications. The core data types in JavaScript are Number, String, Boolean, Object, Function, Array, Date, and Regular Expressions. JavaScript supports features like variables, flow control, error handling, debugging, and JSON for data exchange.
This document provides an overview of JavaScript, including:
- JavaScript is an interpreted programming language used to enhance websites through dynamic content and logic without page refreshes. It has no relation to Java.
- JavaScript can be added inline in HTML or through external files and is typically placed in the <head> section. It is case sensitive.
- Core JavaScript concepts covered include variables, arrays, conditional statements, loops, functions, objects, cookies, dates, math functions, and regular expressions.
- Asynchronous JavaScript and XML (AJAX) allows dynamic updating of web pages using the XMLHttpRequest object to communicate with servers in the background.
Javascript basics for automation testingVikas Thange
油
This document provides an overview of basic JavaScript examples and concepts. It covers topics such as writing JavaScript code, variables, conditional statements, functions, loops, events, and error handling. For each topic, it provides short code snippets to demonstrate the concept. It concludes by referencing W3Schools as a resource and thanking the reader.
This document discusses advanced JavaScript techniques. It covers object-oriented JavaScript concepts like references, function overloading, type checking, scopes, closures, object creation, and inheritance. It also discusses performance improvements like scope management, object caching, and optimizing DOM selection. Finally, it discusses debugging and testing JavaScript code as well as distributing JavaScript applications.
JavaScript is the world's most popular programming language. It is used to add interactive effects to web pages. JavaScript code can be inserted into HTML pages between <script> tags. Common JavaScript statements include conditional statements like if/else and loops. Variables are used to store and manipulate data in JavaScript. Common data types include strings, numbers, booleans, arrays, and objects. Functions allow code reuse and organization. Operators are used to assign values, compare values, and perform arithmetic. jQuery is a popular JavaScript library that simplifies DOM manipulation and event handling.
This document provides an introduction to JavaScript including:
- JavaScript is an object-oriented scripting language that is a dialect of ECMAScript.
- It was originally designed to add interactivity to HTML pages through dynamic HTML, reacting to events, and data validation.
- JavaScript is now heavily used in AJAX-based sites to asynchronously retrieve and display data without reloading pages.
- The document discusses JavaScript compatibility issues and provides examples of basic JavaScript concepts like variables, comparisons, repetition, and popup boxes.
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
油
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
Objects in JavaScript can be created using object literals, the new keyword, or Object.create(). Objects are collections of properties and methods that are mutable and manipulated by reference. Arrays are objects that represent ordered collections of values of any type and are created using array literals or the Array constructor. Common array methods include concat, join, pop, push, reverse, and sort. The Math object provides common mathematical functions like pow, round, ceil, floor, random, and trigonometric functions.
JavaScript is a client-side scripting language that can be inserted into HTML pages to make them interactive. It allows dynamic validation of forms, changing HTML element properties like visibility, and reacting to user events like clicks or form submissions. The Document Object Model (DOM) represents an HTML or XML document as a tree structure, allowing JavaScript to programmatically access and modify the content, structure, and styling of the document. Common built-in JavaScript objects include String, Date, Array, Math, and Boolean, which provide properties and methods for manipulating text, dates, lists of values, numbers, and true/false values.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
This document provides an overview and introduction to JavaScript basics and best practices. It covers what JavaScript is, how engines work, language features, and future developments like ES6. The basics section discusses types, variables, expressions, statements, functions, objects, and prototypical inheritance. The best practices section focuses on techniques for enterprise applications. The document is intended to help front-end developers learn JavaScript fundamentals.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It was originally developed by Netscape as a means to add dynamic content to web pages. JavaScript can be used to create client-side applications, enhance HTML pages with dynamic effects, validate forms, connect to databases, and more. Some key points about JavaScript include that it is embedded directly into HTML, interpreted rather than compiled, loosely typed, object-based, and event-driven. Common JavaScript objects include Window, Document, Location, Form, and more that correspond to HTML elements.
The document provides an overview of JavaScript, covering what it is, its basics, functions, objects, prototypes, scope, asynchronous JavaScript, JSON, debugging tools, performance, events, error handling, and the future of JavaScript. It discusses that JavaScript is an object-oriented scripting language used in web pages that is not tied to specific browsers but makes use of the DOM, BOM, and ECMAScript standards. It also summarizes some of JavaScript's core features like functions, objects, prototypes, and more.
This document discusses JavaScript functions and objects. It explains that functions can return values, run code, and construct objects. It also discusses creating user-defined and built-in objects, accessing and adding properties, and inheritance through the prototype chain. Functions are first-class citizens that can be stored in variables, passed as arguments, and returned from other functions.
JavaScript is the programming language of the web. It can dynamically manipulate HTML content by changing element properties like innerHTML. Functions allow JavaScript code to run in response to events like button clicks or timeouts. JavaScript uses objects and prototypes to define reusable behaviors and properties for objects. It is an important language for web developers to learn alongside HTML and CSS.
Tim Berners-Lee imagined the World Wide Web as a space for interconnecting documents through hyperlinks. He created HTML to provide the structure and formatting for documents, CSS for presentation, and JavaScript for interactivity. These three languages work together to display content on the web. HTML uses tags to mark up content like paragraphs, headings, and images. CSS controls how content is styled and presented using selectors, rules and property-value pairs. It can be linked via external stylesheets, embedded in HTML, or used inline. JavaScript adds interactive behaviors to webpages.
The document discusses secrets and techniques for JavaScript libraries. It covers topics like the JavaScript language, cross-browser code, events, DOM traversal, styles, animations, distribution, and HTML insertion. It provides examples and explanations of techniques for class creation, timers, options, subclassing, custom events, selector internals, computed styles, and dimension calculations.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It explains how prototypal inheritance works by linking objects together through their internal prototype properties. Constructor functions and the new operator allow simulating classical inheritance by establishing prototype links. Various design patterns are also covered, such as public/privileged methods, singletons, modules, and parasitic inheritance.
In recent years we have seen explosion of languages which run on Java Virtual Machine. We also have seen existing languages getting their implementations being rewritten to JVM. With all of the above we have seen rapid development of tools like parsers, bytecode generators and such, even inside JVM we saw initiatives like Da Vinci Machine Project, which led to invoke dynamic in JDK 7 and recent development of Graal and Truffle projects.
Is it really hard to write new programming language running on JVM? Even if you are not going to write your own I think it is worth to understand how your favorite language runs undercover, how early decisions can impact language extensibility and performance, what JVM itself and JVM ecosystem has to offer to language implementors.
During session I will try to get you familiar with options you have when choosing parsers and byte code manipulation libraries. which language implementation to consider, how to test and tune your "new baby". Will you be able after this session to develop new and shiny language, packed with killer features language? No. But for sure you will understand difference between lexers and parsers, how bytecode works, why invoke dynamic and Graal and Truffle are so important to the future of JVM platform. Will we have time to write simple, compiled language?
Yes, we will, just to show you that even person who didn't studied computer science, compilers theory, and for majority of his life didn't know what AST is, can do it :)
JavaScript is a scripting language that can be inserted into HTML pages and used to program the behavior of web pages. It allows web pages to be dynamic and interactive. JavaScript code is placed between <script> and </script> tags and can manipulate HTML elements and write to the document. Variables, functions, conditional statements, and operators allow JavaScript code to run conditionally based on events or user input. JavaScript is case sensitive, uses semicolons, and has both local and global variables. Common data types include numbers, strings, arrays, and objects.
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
This document provides an introduction to JavaScript, covering basic concepts like data types, variables, operators, conditionals, loops, functions, arrays, and objects. It explains that JavaScript is an interpreted language that allows dynamic and interactive functionality on websites. Key points are demonstrated through examples, like using alert to output "Hello World" and basic math operations with variables.
This document provides best practices for writing JavaScript code. It recommends using strict comparison operators (=== and !==), declaring variables with 'var' to avoid globals, adding comments with /* */, using object literals for configuration, validating external data, optimizing loops, and using dot and bracket notation wisely based on property visibility. Braces {} should be used to clearly delimit blocks. Variable types should not be changed after declaration and shortcuts like conditionals (?:) can optimize code.
This document provides an overview of JavaScript including:
1. How JavaScript code can be embedded in HTML pages using <script> tags internally or externally.
2. How JavaScript code is executed, with code outside of functions running on page load and code in functions only running when called.
3. The structure of JavaScript functions and how they are used to return values.
4. How external JavaScript files can be used to store common functions for reuse across multiple HTML pages.
5. The basic language elements of JavaScript like variables, data types, and operators.
This document provides an overview of JavaScript basics including variables, data types, operators, conditional statements, loops, functions, arrays, and error handling. It explains JavaScript syntax, how to include JavaScript code in HTML pages, and commonly used statements like if/else, switch case, while and for loops. It also covers JavaScript functions, returning values from functions, and printing pages. The document describes JavaScript strings and array objects, and their associated methods. Finally, it discusses different types of errors in JavaScript like syntax errors, runtime errors, and logical errors.
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
油
You all might have downloaded and edited a lot of javascript. Other than merely changing syntax have you really understood its working or how the code was organised ?
Have you ever thought of how the object oriented way of writing Javascript has been influencing the front end development?
From a language that had helped developers write small validations and similar stuff, today, the object oriented javascript and its frameworks power the world becoming one of the most prominent language of all times.
Javascript allows interactive content on web pages and control of the browser and document. It is an interpreted scripting language that is cross-platform but support varies. Javascript can provide interactive content, control document appearance and content, and interact with the user through event handlers.
Objects in JavaScript can be created using object literals, the new keyword, or Object.create(). Objects are collections of properties and methods that are mutable and manipulated by reference. Arrays are objects that represent ordered collections of values of any type and are created using array literals or the Array constructor. Common array methods include concat, join, pop, push, reverse, and sort. The Math object provides common mathematical functions like pow, round, ceil, floor, random, and trigonometric functions.
JavaScript is a client-side scripting language that can be inserted into HTML pages to make them interactive. It allows dynamic validation of forms, changing HTML element properties like visibility, and reacting to user events like clicks or form submissions. The Document Object Model (DOM) represents an HTML or XML document as a tree structure, allowing JavaScript to programmatically access and modify the content, structure, and styling of the document. Common built-in JavaScript objects include String, Date, Array, Math, and Boolean, which provide properties and methods for manipulating text, dates, lists of values, numbers, and true/false values.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
This document provides an overview and introduction to JavaScript basics and best practices. It covers what JavaScript is, how engines work, language features, and future developments like ES6. The basics section discusses types, variables, expressions, statements, functions, objects, and prototypical inheritance. The best practices section focuses on techniques for enterprise applications. The document is intended to help front-end developers learn JavaScript fundamentals.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It was originally developed by Netscape as a means to add dynamic content to web pages. JavaScript can be used to create client-side applications, enhance HTML pages with dynamic effects, validate forms, connect to databases, and more. Some key points about JavaScript include that it is embedded directly into HTML, interpreted rather than compiled, loosely typed, object-based, and event-driven. Common JavaScript objects include Window, Document, Location, Form, and more that correspond to HTML elements.
The document provides an overview of JavaScript, covering what it is, its basics, functions, objects, prototypes, scope, asynchronous JavaScript, JSON, debugging tools, performance, events, error handling, and the future of JavaScript. It discusses that JavaScript is an object-oriented scripting language used in web pages that is not tied to specific browsers but makes use of the DOM, BOM, and ECMAScript standards. It also summarizes some of JavaScript's core features like functions, objects, prototypes, and more.
This document discusses JavaScript functions and objects. It explains that functions can return values, run code, and construct objects. It also discusses creating user-defined and built-in objects, accessing and adding properties, and inheritance through the prototype chain. Functions are first-class citizens that can be stored in variables, passed as arguments, and returned from other functions.
JavaScript is the programming language of the web. It can dynamically manipulate HTML content by changing element properties like innerHTML. Functions allow JavaScript code to run in response to events like button clicks or timeouts. JavaScript uses objects and prototypes to define reusable behaviors and properties for objects. It is an important language for web developers to learn alongside HTML and CSS.
Tim Berners-Lee imagined the World Wide Web as a space for interconnecting documents through hyperlinks. He created HTML to provide the structure and formatting for documents, CSS for presentation, and JavaScript for interactivity. These three languages work together to display content on the web. HTML uses tags to mark up content like paragraphs, headings, and images. CSS controls how content is styled and presented using selectors, rules and property-value pairs. It can be linked via external stylesheets, embedded in HTML, or used inline. JavaScript adds interactive behaviors to webpages.
The document discusses secrets and techniques for JavaScript libraries. It covers topics like the JavaScript language, cross-browser code, events, DOM traversal, styles, animations, distribution, and HTML insertion. It provides examples and explanations of techniques for class creation, timers, options, subclassing, custom events, selector internals, computed styles, and dimension calculations.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It explains how prototypal inheritance works by linking objects together through their internal prototype properties. Constructor functions and the new operator allow simulating classical inheritance by establishing prototype links. Various design patterns are also covered, such as public/privileged methods, singletons, modules, and parasitic inheritance.
In recent years we have seen explosion of languages which run on Java Virtual Machine. We also have seen existing languages getting their implementations being rewritten to JVM. With all of the above we have seen rapid development of tools like parsers, bytecode generators and such, even inside JVM we saw initiatives like Da Vinci Machine Project, which led to invoke dynamic in JDK 7 and recent development of Graal and Truffle projects.
Is it really hard to write new programming language running on JVM? Even if you are not going to write your own I think it is worth to understand how your favorite language runs undercover, how early decisions can impact language extensibility and performance, what JVM itself and JVM ecosystem has to offer to language implementors.
During session I will try to get you familiar with options you have when choosing parsers and byte code manipulation libraries. which language implementation to consider, how to test and tune your "new baby". Will you be able after this session to develop new and shiny language, packed with killer features language? No. But for sure you will understand difference between lexers and parsers, how bytecode works, why invoke dynamic and Graal and Truffle are so important to the future of JVM platform. Will we have time to write simple, compiled language?
Yes, we will, just to show you that even person who didn't studied computer science, compilers theory, and for majority of his life didn't know what AST is, can do it :)
JavaScript is a scripting language that can be inserted into HTML pages and used to program the behavior of web pages. It allows web pages to be dynamic and interactive. JavaScript code is placed between <script> and </script> tags and can manipulate HTML elements and write to the document. Variables, functions, conditional statements, and operators allow JavaScript code to run conditionally based on events or user input. JavaScript is case sensitive, uses semicolons, and has both local and global variables. Common data types include numbers, strings, arrays, and objects.
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
This document provides an introduction to JavaScript, covering basic concepts like data types, variables, operators, conditionals, loops, functions, arrays, and objects. It explains that JavaScript is an interpreted language that allows dynamic and interactive functionality on websites. Key points are demonstrated through examples, like using alert to output "Hello World" and basic math operations with variables.
This document provides best practices for writing JavaScript code. It recommends using strict comparison operators (=== and !==), declaring variables with 'var' to avoid globals, adding comments with /* */, using object literals for configuration, validating external data, optimizing loops, and using dot and bracket notation wisely based on property visibility. Braces {} should be used to clearly delimit blocks. Variable types should not be changed after declaration and shortcuts like conditionals (?:) can optimize code.
This document provides an overview of JavaScript including:
1. How JavaScript code can be embedded in HTML pages using <script> tags internally or externally.
2. How JavaScript code is executed, with code outside of functions running on page load and code in functions only running when called.
3. The structure of JavaScript functions and how they are used to return values.
4. How external JavaScript files can be used to store common functions for reuse across multiple HTML pages.
5. The basic language elements of JavaScript like variables, data types, and operators.
This document provides an overview of JavaScript basics including variables, data types, operators, conditional statements, loops, functions, arrays, and error handling. It explains JavaScript syntax, how to include JavaScript code in HTML pages, and commonly used statements like if/else, switch case, while and for loops. It also covers JavaScript functions, returning values from functions, and printing pages. The document describes JavaScript strings and array objects, and their associated methods. Finally, it discusses different types of errors in JavaScript like syntax errors, runtime errors, and logical errors.
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
油
You all might have downloaded and edited a lot of javascript. Other than merely changing syntax have you really understood its working or how the code was organised ?
Have you ever thought of how the object oriented way of writing Javascript has been influencing the front end development?
From a language that had helped developers write small validations and similar stuff, today, the object oriented javascript and its frameworks power the world becoming one of the most prominent language of all times.
Javascript allows interactive content on web pages and control of the browser and document. It is an interpreted scripting language that is cross-platform but support varies. Javascript can provide interactive content, control document appearance and content, and interact with the user through event handlers.
This document provides an introduction to JavaScript and the DOM. It begins with an overview of the author's background and experience. It then covers JavaScript fundamentals like data types, objects, functions, and events. It also discusses the DOM and how to access and manipulate elements using methods like getElementById, querySelector, and properties like childNodes. The document is intended as a basic JavaScript and DOM primer.
Prototype JS is a JavaScript framework that simplifies DOM manipulation, AJAX requests, and other common tasks. It provides functions for DOM traversal and manipulation, event handling, effects and animations, forms, JSON, and more. Developers use Prototype to build dynamic web pages and applications with less code and cross-browser compatibility.
The document provides an overview of JavaScript for a beginner audience. It discusses what JavaScript is, why it is used, examples of its capabilities, and how to write JavaScript code. The session will demonstrate JavaScript capabilities, explain code samples, and answer questions. JavaScript allows dynamic functionality on web pages by manipulating the browser and document object model (DOM).
This document provides an overview of JavaScript reversing techniques. It discusses JavaScript technologies like the DOM, Ajax, and JSON. It covers security aspects like the same-origin policy. It provides tips for analyzing JavaScript using tools like Firebug. It also demonstrates finding vulnerabilities like DOM-based XSS and reversing obfuscated JavaScript.
JavaScript is a scripting language that allows adding interactivity to HTML pages. It can react to events, read and write HTML elements, validate data, detect the visitor's browser, create cookies, and more. The DOM defines a standard for accessing and manipulating HTML documents. JavaScript uses objects, functions, and prototypes for object-oriented programming. Key concepts include encapsulation, inheritance, and abstraction. Events follow the capturing and bubbling phases. JavaScript supports conditionals, loops, functions, scopes, closures, and more.
JavaScript can dynamically manipulate the content, structure, and styling of an HTML document through the Document Object Model (DOM). The DOM represents an HTML document as nodes that can be accessed and modified with JavaScript. Common tasks include dynamically creating and adding elements, handling user events like clicks, and updating content by accessing DOM elements by their id or other attributes.
The document provides an introduction to JavaScript, including:
1) Why JavaScript was created, its syntax, and how to include it in HTML documents.
2) How JavaScript objects work and some predefined JavaScript objects like Math, String, and Array.
3) Examples of JavaScript functions, strings, and how to manipulate elements using the DOM.
4) JavaScript events and how code can run when events occur on HTML elements.
5) Methods for accessing and modifying DOM elements directly through properties, IDs, and collections.
1. The document introduces object-oriented JavaScript and demonstrates how to define classes using constructor functions and prototypes. It shows how to create Lecture and Schedule classes.
2. Events and interacting with the DOM are discussed. Methods are shown for getting DOM elements and adding event listeners to manipulate elements on mouseover and mouseout.
3. The relationship between JavaScript, CSS, and AJAX is briefly covered, along with browser support considerations for modern JavaScript development.
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
油
The document summarizes Peter Serzo's presentation on the client-side story and object model in SharePoint 2010. It discusses how the client object model allows accessing SharePoint data through managed code, Silverlight, JavaScript and web services. It provides examples of using the client object model to upload files, retrieve list data, and get user profile properties. It also covers using jQuery templates and REST to display and format list data on a page.
This document provides an introduction to JSON (JavaScript Object Notation), including what it is, its data structure, how to send and receive JSON data at both the client and server sides, and resources for further information. The key points covered are:
- JSON is a lightweight data format that is easy for humans and machines to read/write and is independent of programming languages.
- JSON data is structured as either a collection of name/value pairs (objects) or an ordered list of values (arrays).
- JSON can be converted to and from JavaScript objects using functions like eval() and JSON.parse().
- At the server, JSON data can be generated from objects and sent to clients, then parsed at the
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It uses conventions like those in C and Java and is built on two structures: a collection of name/value pairs and an ordered list of values. JSON is commonly used to transmit data between a server and web application, with the server side formatting data into JSON and the client side parsing the JSON into native JavaScript objects.
This document provides summaries of key points about the jQuery and Prototype JavaScript libraries:
1. jQuery is an open-source JavaScript library that simplifies HTML document traversal, event handling, animation, and Ajax interactions. It has a lightweight footprint and is cross-browser compatible.
2. Both jQuery and Prototype are available under MIT and GPL licenses, allowing developers to choose the license that best suits their projects. jQuery is maintained by a core team and has additional community support.
3. The document then provides examples of common jQuery functions and selectors for manipulating the DOM, handling events, animating elements, and making Ajax requests.
This document provides summaries of key points about the jQuery and Prototype JavaScript libraries:
1. jQuery is an open-source JavaScript library that simplifies HTML document traversal, event handling, animation, and Ajax interactions. It has a lightweight footprint and is cross-browser compatible.
2. Both jQuery and Prototype are available under MIT and GPL licenses, allowing developers to choose the license that best suits their projects. jQuery is maintained by a core team and has additional community support.
3. The document then provides examples of common jQuery functions and selectors for manipulating the DOM, handling events, animating elements, and making Ajax requests.
Ajax, JSON & jQuery
"JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
json.org
JSON is often used in Ajax calls instead of XML because its more lightweight compared to XML, less text is needed for defining the same data.
This document discusses several JavaScript design patterns including singleton, module, engine, event-driven programming, and templates. It provides code examples and explanations for each pattern. The patterns are introduced as ways to make programming easier by improving code organization, reuse, separation of concerns, and error handling.
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 (contd) 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: " 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(); };
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("The date to format:"+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 : ""); 油油 油 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 "userID" }
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 //"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); 油 } }
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 "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. JSON taglib JSON for Java
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="skillDeleteRows('+array[0]+');" style="cursor: pointer"><img src=/slideshow/javascripttemplating/1466488/"/images/button_trash.gif alt="Remove"/></a>'+'<input type="hidden" name="skillIds" value="'+array[0]+'"/>'; By using a template, you can make this code look more like code (no escaping, no + stuff, etc): <a onclick="skillDeleteRows(${data.id});" style="cursor:pointer;"> 油 <img src="/images/button_trash.gif" alt="Remove"/> </a> <input type="hidden" name="skillIds" value="${data.id}"/>
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));
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("there was an issue with the server:"+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')); }