JavaScript Libraries: Prototype.js. Get it at:

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 16 Introduction to Ajax.
Advertisements

JavaScript & jQuery JavaScript and jQuery introduction.
JavaScript and AJAX Jonathan Foss University of Warwick
Intro to JavaScript. JavaScript History Client (generally browser-side) language invented at Netscape under the name LiveScript around 1995 Netscape wanted.
The DOM tree CS The DOM tree CS380 2 Types of DOM nodes  element nodes (HTML tag)  can have children and/or attributes  text nodes (text in.
JQuery CS 380: Web Programming. What is jQuery? jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling,
JQuery A Javascript Library Hard things made eas(ier) Norman White.
Ajax. Overview of Ajax History In the 1990s, most web sites were based on complete HTML pages; each user action required that the page be re-loaded from.
Writing jQuery Plugins Jon Hartmann Most content shamelessly stolen from and
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
9. AJAX & RIA. 2 Motto: O! call back yesterday, bid time return. — William Shakespeare.
19-Jun-15 Ajax. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better, faster,
JAVASCRIPT Introduction Kenny Lam. What is Javascript?  Client-side scripting language that can manipulate elements in the DOM  Event-driven language.
JQuery. What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library that simplifies HTML document traversing and manipulation event handling.
Philly.NET Hands-On jQuery + Plug-ins Bill Wolff, Rob Keiser.
User Interface Design using jQuery Mobile CIS 136 Building Mobile Apps 1.
Chapter 6 DOJO TOOLKITS. Objectives Discuss XML DOM Discuss JSON Discuss Ajax Response in XML, HTML, JSON, and Other Data Type.
JQuery CS 268. What is jQuery? From their web site:
NextGen Technology upgrade – Synerizip - Sandeep Kamble.
Christopher Paolini Computational Science Research Center College of Engineering San Diego State University Computational Science 670 Fall 2009 Monday.
Bringing pages to life with jQuery BEAR BIBEAULT YEHUDA KATZ.
PhpXperts What is jQuery Javascript Library Fast and concise Simplifies the interaction between HTML and JavaScript.
2 Alerts and the If/Else Conditional Statement CONTINUED There's No Right Way to Do It There are, literally, a million ways to write any given script.
JavaScript, jQuery & AJAX. What is JavaScript? An interpreted programming language with object oriented capabilities. Not Java! –Originally called LiveScript,
JavaScript & jQuery the missing manual Chapter 11
Tutorial 14 Working with Forms and Regular Expressions.
Step Outside the Box – Part II ColdFusion and Ajax.
JQuery 10/21. Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
SERVER web page repository WEB PAGE instructions stores information and instructions BROWSER retrieves web page and follows instructions Server Web Server.
Arrays – What is it? – Creation – Changing the contents Functions – What is it? – Syntax – How they work – Anonymous functions A quick lesson in Objects.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 16 Introduction to Ajax.
INTRODUCTION TO HTML5 Using jQuery with HTML5. Introducing jQuery  Although it is not a part of any W3C or WHATWG specification, jQuery performs an important.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Developing AJAX Web applications with Castle Monorail David De Florinier Gojko Adzic Skills Matter 12/06/08.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Dimiter Kunchev.  JavaScript library written by Sam Stephenson   Adds object oriented techniques  Provides.
Unleash the Power of jQuery Learning & Development Team Telerik Software Academy.
Review of the DOM Node properties and methods Some ways of accessing nodes Appending, copying and removing nodes Event handling – Inline – Scripting –
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
Creating Dynamic Webpages
CSE 341 Lecture 25 More about JavaScript functions slides created by Marty Stepp
Unit 10 – JavaScript Validation Instructor: Brent Presley.
Intro to jQuery. What is jQuery? A JavaScript library Lightweight (about 31KB for the minified version) Simplifies HTML document traversing (DOM), event.
Unit 13 –JQuery Basics Instructor: Brent Presley.
AJAX. Overview of Ajax Ajax is not an API or a programming language Ajax aims to provide more responsive web applications In normal request/response HTTP.
1 Javascript CS , Spring What is Javascript ? Browser scripting language  Dynamic page creation  Interactive  Embedded into HTML pages.
AJAX in Ruby-on-Rails. Ruby on Rails and AJAX AJAX can be done with just Javascript Easier if you use libraries –Prototype –SAJAX –jQuery Libraries only.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
JQuery form submission CIS 136 Building Mobile Apps 1.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library.
JQuery.
Introduction to.
JavaScript, Sixth Edition
Prototype.
CGS 3066: Web Programming and Design Spring 2017
JQUERY Online TRAINING AT GOLOGICA
COP3530- Data Structures Javascript
Web Programming and Design
Presentation transcript:

JavaScript Libraries: Prototype.js

Get it at:

Prototype.js Ajax interface Utility methods Helper methods Extending the DOM Class Object …and even more!

AJAX interface Three objects that give you the simplest method for AJAXifying your applications: –Ajax.PeriodicalUpdater –Ajax.Updater –Ajax.Request Also provides the ability to register global listeners for each step of the AJAX requests using Ajax.Responders

Ajax.PeriodicalUpdater new Ajax.PeriodicalUpdater(container, url[,options]) Updates the container with the contents of the response text Options: –Frequency: number of seconds between calls (default is 2) –Decay: rate at which the request interval grows when the response in unchanged (default is 1 – or no decay)

Ajax.Updater new Ajax.Updater(container, url[, options]) Replaces innerHTML of container with response text

Ajax.Request new Ajax.Request(url[, options]) Callbacks allow you to build custom functionality with the response text instead of just replacing innerHTML of container element.

Ajax.Responders Repository of global event listeners for each step of the AJAX request. Use register() and unregister() methods Example: Ajax.Responders.register({ onCreate: function() { Ajax.activeRequestCount++; toggleIndicator(); }, onComplete: function() { Ajax.activeRequestCount--; toggleIndicator(); } });

Ajax Options Available options: –method, –parameters, –asynchronous, –postBody, –requestHeaders, –insertion, –evalScripts, –decay (periodicalUpdater), –frequency (periodicalUpdater)

Ajax Callbacks The following are commonly used callbacks that receive the XHR object and the result of evaluating the X_JSON response header if applicable: –onSuccess, –onFailure, –onException, –onComplete

Ajax Callbacks example var myObject = Class.create(); Object.extend(myObject.prototype, { initialize: function(options){ this.setoptions(options) }, setoptions: function(options) { this.options = { ajaxurl: 'ajaxcalls.cfm', mydivid: 'mydiv' } Object.extend(this.options, options || {}); }, myAjaxCall: function(){ var pars = 'action=returntrue'; var myAjax = new Ajax.Request(this.options.ajaxurl, {method: 'post', parameters: pars, onSuccess: this.processMyAjax.bindAsEventListener(this)}); }, processMyAjax: function(t){ if (t.responseText.strip() == 1) $(this.options.mydivid).innerHTML = 'Hello, world!'; else window.alert('There was an error'); } }); Event.observe(window,'load',function(){myobj = new myObject();});

Utility Methods $ $$ $A $F $H $R $w try.these document.getElementsByClassName

$() method document.getElementById() on steroids Pass in id or element Pass in multiple ids will return an Array object of all elements

$() example function alertDivs(){ 6.var divNodes = $('div1','div2'); 7.divNodes.each(function(node){ 8.window.alert(node.innerHTML); 9.}); 10.} Dollar Method Hello, 15. World! 16. Alert Divs

$$() method Specify any CSS rule –Type selectors (div) –Descendent selector (space between selectors) –Attribute selectors ([attr],[attr=value],etc…) –Class selectors (.classname) –ID selectors (#div1) Returns a document-order Array of elements that match the CSS rule All elements inherit Prototype’s DOM Extensions

$$() method When to NOT use: –You want elements with a specified CSS class name use: document.getElementsByClassName() –You want elements with a specified CSS class name within a container element use: Element.getElementsByClassName()

$$() example function alertDivs(){ var divNodes = $$('div.helloworld'); divNodes.each(function(node){ window.alert(node.innerHTML); }); } Dollar Method Hello, World! Not me? Alert Divs

$A() method $A(iterable) Takes an “array-like collection” – that’s anything with an numeric indices Often used for DOM functions that return the HTMLCollection object (an abstract representation in the W3C DOM of any collection of HTML element objects) Provides the ability to use Prototype’s extended Array class with the Enumerable module i.e. –document.images –document.getElementByTagName() –element.childNodes

$A() example function alertDivs(){ var divs = document.getElementsByTagName('div'); var divNodes = $A(divs); divNodes.each(function(node){ window.alert(node.innerHTML); }); } Dollar Method Hello, World! Here we go again! Alert Divs

$F() method $F(element) Returns the current value of a form control The current value is a string for all controls except multiple select boxes, which return an array of values. As a side note: Really, this is just a global shortcut method for Form.Element.getValue(element)

$H() method $H([obj]) Returns instance of a Hash object (instead of regular JS object instantiation using the new keyword, which returns a clone of the hash – keeping the original intact).

What’s a Hash? Hashes are associative arrays In ColdFusion, we refer to these as Structs Prototype extends these as well (as we’ll see later) with the Enumerable module

$H() example function alertDivs(){ var h = $H({name: 'value', myfunction: function(){ window.alert('This is my function!'); }}); h.myfunction(); } Hash Example Alert my function

$R() method $R(start, end[, exclusive = false]) Creates a new ObjectRange object Returned Array is extended with Prototype’s Enumerable module

$R() examples $R(0, 10).include(10) // -> true $A($R(0, 5)).join(', ') // -> '0, 1, 2, 3, 4, 5' $A($R('aa', 'ah')).join(', ') // -> 'aa, ab, ac, ad, ae, af, ag, ah' $R(0, 10, true).include(10) // -> false $R(0, 10, true).each(function(value) { // invoked 10 times for value = 0 to 9 });

$w() method Splits a string into an Array, treating all whitespace as delimiters Returned Array is extended with Prototype’s Enumerable class

You keep saying: ‘The element is extended with Prototype’s DOM extensions’ or ‘The returned Array is extended with Prototype’s Enumerable module’

What the heck are you talking about?

I’m talking about Helpers… Enumerables –Arrays –Hashes –Ranges Element.Methods Event Form Function Insertion Class Object

Enumerables all any collect detect each entries find findAll grep include Inject invoke map max member min partition pluck reject select size sortBy toArray zip

Array Helpers Array is extended with Enumerable module Array is also extended with the following methods: –clear() –clone() –compact() –each() –first() and last() –flatten() –from() –indexOf() –reverse() –uniq() –without()

Hash Helpers Hash is extended with Enumerable module Hash is also extended with the following methods: –each() –inspect() –keys() –merge() –remove() –toQueryString() –values()

Element.Methods Prototype extends DOM elements Accessed via: –$() utility method, i.e.: $(‘mydiv’).addClassName(‘highlight’); –Element object, i.e.: Element.addClassName(‘mydiv’,’highlight’); –Or directly as methods of an extended element using Element.extend(), i.e.: say we have an: onclick=“highlight(this)” function highlight(elem){ Element.extend(elem); elem.addClassName(‘highlight’); }

Commonly used Element methods addClassName() and removeClassName() addMethods() cleanWhitespace() extend() hide() and show() getElementsByClassName() setStyle() scrollTo() update() and more…

Element.methods Most methods return the element, so you can also chain these together, i.e.: $(‘mydiv’).addClassName(‘highlight’).upda te(‘Changes have been saved’).toggle();

Event Events management made easy! Commonly used methods: –observe() and stopObserving() –findElement()

Event example Event.observe(‘mydiv’,’click’,myFunction); Event.stopObserving(‘mydiv’,’click’,myFunction); Now, lets say we are using the this reference within a function, such as: var myObj = { ajaxurl: 'ajaxcalls.cfm', indicatorid: 'ajaxindicator', toggleIndicator: function(){ $(this.indicatorid).toggle(); }, myFunction: function(){ new Ajax.Request(this.ajaxurl,{parameters: pars, onSuccess: this.myFunctionHandler}); }, myFunctionHandler: function(t){ if (t.responseText.strip() == 1){ this.toggleIndicator; }else{ window.alert('There was an error'); }

The problem with this When you pass the myFunctionHandler as a function argument you lose what this means to the original function When we call this.toggleIndicator() within the myFunctionHandler() method without using Prototype’s binding, toggleIndicator() will not be called. Prototype solves this with bind() and bindAsEventListener() –The only difference is that bindAsEventListener() ensures the first argument to the function is the event object

Binding solved, thanks Prototype! var myObj = { ajaxurl: 'ajaxcalls.cfm', indicatorid: 'ajaxindicator', toggleIndicator: function(){ $(this.indicatorid).toggle(); }, myFunction: function(){ new Ajax.Request(this.ajaxurl,{parameters: pars, onSuccess: this.myFunctionHandler.bindAsEventListener(this)}); }, myFunctionHandler: function(t){ if (t.responseText.strip() == 1){ this.toggleIndicator; }else{ window.alert('There was an error'); } What does it do? Pretty simple actually: Prototype wraps the function in another one, which locks the execution scope to an object that is specified as the first argument

Class Object Prototype extends the OO nature of JS Class.create() returns a function that acts like a Ruby class, that when called will fire its own initialize() method.

Class example var Sports = Class.create(); Sports.prototype = { initialize: function(name,action,point){ this.name = name; this.action = action; this.point = point; }, score: function(){ window.alert('The '+this.name+' player '+this.action+' a '+this.point); } var rball = new Sports('racquetball','served','ace'); rball.score(); // -> alerts 'The racquetball player served a ace' var bball = new Sports('baseball','hit','homerun'); bball.score(); // -> alerts 'The baseball player hit a homerun' //lets extend the Sports class to create a Swimming class var Swimming = Class.create(); Swimming.prototype = Object.extend(new Sports(), { score: function(){ window.alert('The '+this.name+'\'s time was '+this.point); } }); var swimmer = new Swimming('swimmer','','1 minute and 2 seconds'); swimmer.score(); // -> alerts 'The swimmer's time was 1 minute and 2 seconds'