Prototype - Quick Guide



Prototype - Overview

What is Prototype ?

Prototype is a JavaScript Framework that aims to ease the development of dynamic web applications. Prototype was developed by Sam Stephenson.

Prototype is a JavaScript library, which enables you to manipulate DOM in a very easy and fun way that is also safe (cross-browser).

Scriptaculous and other libraries, such as Rico are build on Prototype's foundations to create widgets and other end-user stuff.

Prototype

  • Extends DOM elements and built-in types with useful methods.

  • Has built-in support for class-style OOP including inheritance.

  • Has advanced support for event management.

  • Has powerful Ajax features.

  • Is not a complete application development framework.

  • Does not provide widgets or a full set of standard algorithms or I/O systems.

How to Install Prototype?

Prototype is distributed as a single file called prototype.js. Follow the below mentioned steps to setup the prototype library −

  • Go to the download page (http://prototypejs.org/download/) to grab the latest version in a convenient package.

  • Now, put prototype.js file in a directory of your website, e.g. /javascript.

You are now ready to use the powerful Prototype framework in your web pages.

How to Use Prototype Library?

Now, you can include the Prototype script as follows −

<html>
   <head>
      <title>Prototype examples</title> 
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
   </head>
   
   <body>
      ........
   </body>
</html>

Example

Here is a simple example showing how you can use Prototype's $() function to get DOM elements in your JavaScript −

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function test() {
            node = $("firstDiv");
            alert(node.innerHTML);
         }
      </script>
   </head>

   <body>
      <div id = "firstDiv">
         <p>This is first paragraph</p> 
      </div>
      
      <div id = "secondDiv">
         <p>This is another paragraph</p>
      </div>
      
      <input type = "button" value = "Test $()" onclick = "test();"/>
   </body>
</html>

Output

Why This Tutorial?

A very good documentation for Prototype Framework is available at prototypejs.org then why should one refer to this tutorial!

The answer is that we have put all the most commonly used functionalities together in this tutorial. Secondly, we have explained all the useful methods along with suitable examples, which are not available at the official site.

If you are an advanced user of Prototype Framework, then you can directly jump to the official website, otherwise this tutorial could be a good start for you and you can use it like a reference manual.

Prototype - Useful Features

Let's now look at what Prototype can do specifically for us to develop a Dynamic Web Application.

Cross Browser Support

While doing JavaScript programming, it is required to handle different Web Browsers differently. Prototype Library has been written in such a way that it takes care of all the compatibility issues and you can do cross browser programming without any hassle.

The Document Object Model

Prototype provides helper methods that ease some of the strain of DOM programming. Using Prototype, you can manipulate DOM very easily.

HTML Forms

With Ajax, other input mechanisms such as drag and drop, can be used as part of a conversation between the browser and the server. With conventional JavaScript programming, it is difficult to capture these inputs and pass them to the server. Prototype provides a set of utilities for working with HTML forms.

JavaScript Events

Prototype provides some excellent cross-browser support while coding events, and also extends the Function object to make it easy to work with event handling.

Ajax Utilities

The most important feature of Prototype is it's support for Ajax. All major browsers support a version of the XMLHttpRequest object that makes Ajax possible, either as an ActiveX component or as a native JavaScript object.

XMLHttpRequest, however, exposes the HTTP protocol at a very low level, which gives the developer a lot of power, but also requires her to write a lot of code in order to do simple things.

Prototype uses it's own object inheritance system to provide a hierarchy of Ajax helper objects, with more generic base classes being subclassed by more focused helpers that allow the most common types of Ajax request to be coded in a single line.

Prototype - Utility Methods

The Prototype library comes with lot of predefined objects and utility functions. You can use those functions and objects directly in your JavaScript programming.

These methods are one of the cornerstones of efficient Prototype-based JavaScript coding. Spend some time to study them to become comfortable with the methods.

This chapter details all these useful methods with examples.

S.No. Method & Description
1. $()

If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element.

2. $$()

Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended DOM elements that match any of them.

3. $A()

Converts the single argument it receives into an Array object.

4. $F()

Returns the value of a form control. This is a convenience alias of Form.Element.getValue.

5. $H()

Converts objects into enumerable Hash objects that resemble associative arrays.

6. $R()

Creates a new ObjectRange object.

7. $w()

Splits a string into an Array, treating all whitespace as delimiters.

8. Try.these

Accepts an arbitrary number of functions and returns the result of the first one that doesn't throw an error.

document.getElementsByClassName

This method retrieves (and extends) all the elements that have a CSS class name of className.

However, this method has been deprecated in the latest versions of Prototype.

Prototype - Element Object

The Element object provides various utility functions for manipulating elements in the DOM.

Here is the list of all the utility functions with examples. All the methods defined here are automatically added to any element accessed using the $() function.

So, writing Element.show('firstDiv'); is the same as writing $('firstDiv').show();

Prototype Element Method

NOTE − Make sure you have at least version 1.6 of prototype.js.

S.No. Method & Description
1. absolutize()

Turns element into an absolutely-positioned element without changing its position in the page layout.

2. addClassName()

Adds the given CSS class name to the element's class names.

3. addMethods()

Makes it possible to mix in your own methods to the Element object, which you can later use as methods of extended elements.

4. adjacent()

Finds all siblings of the current element that match the given selector(s).

5. ancestors()

Collects all of element's ancestors and returns them as an array of extended elements.

6. childElements()

Collects all of the element's children and returns them as an array of extended elements.

7.

classNames()

Deprecated. Returns a new instance of ClassNames, an Enumerable object used to read and write CSS class names of element.

8. cleanWhitespace()

Removes all of element's text nodes, which contain only whitespace. Returns element.

9. clonePosition()

Clones the position and/or dimensions of source onto element as defined by the optional argument options.

10. cumulativeOffset()

Returns the offsets of element from the top left corner of the document.

11. cumulativeScrollOffset()

Calculates the cumulative scroll offset of an element in nested scrolling containers.

12. descendantOf()

Checks if the element is a descendant of ancestor.

13. descendants()

Collects all of element's descendants and returns them as an array of extended elements.

14. down()

Returns element's first descendant that matches cssRule. If no cssRule is provided, all descendants are considered. If no descendant matches these criteria, undefined is returned.

15. empty()

Tests whether element is empty (i.e., contains only whitespace).

16. extend()

Extends element with all of the methods contained in Element.Methods and Element.Methods.Simulated.

17. fire()

Fires a custom event with the current element as its target.

18. firstDescendant()

Returns the first child that is an element. This is opposed to firstChild DOM property, which will return any node.

19. getDimensions()

Finds the computed width and height of an element and returns them as key/value pairs of an object.

20.

getElementsByClassName

Deprecated. Fetches all of element's descendants, which have a CSS class of className and returns them as an array of extended elements. Please use $$().

21.

getElementsBySelector

Deprecated. Takes an arbitrary number of CSS selectors (strings) and returns an array of extended children of element that match any of them. Please use $$().

22. getHeight()

Finds and returns the computed height of element.

23. getOffsetParent()

Returns element's closest positioned ancestor. If none is found, the body element is returned.

24. getStyle()

Returns the given CSS property value of element. Property can be specified in either of its CSS or camelized form.

25. getWidth()

Finds and returns the computed width of element.

26. hasClassName()

Checks whether element has the given CSS className.

27. hide()

Hides and returns element.

28. identify()

Returns element's id attribute if it exists, or sets and returns a unique, auto-generated id.

29.

immediateDescendants()

Deprecated. Collects all of the element's immediate descendants (i.e., children) and returns them as an array of extended elements. Please use childElements().

30. insert()

Inserts content before, after, at the top of, or at the bottom of element.

31. inspect()

Returns the debug-oriented string representation of element.

32. makeClipping()

Simulates the poorly supported CSS clip property by setting element's overflow value to 'hidden'. Returns element.

33. makePositioned()

Allows for the easy creation of CSS containing block by setting element's CSS position to 'relative' if its initial position is either 'static' or undefined. Returns element.

34. match()

Checks if element matches the given CSS selector.

35. next()

Returns element's following sibling that matches the given cssRule.

36. nextSiblings()

Collects all of element's next siblings and returns them as an array of extended elements.

37. observe()

Registers an event handler on element and returns element.

38. positionedOffset()

Returns element's offset relative to its closest positioned ancestor.

39. previous ()

Returns element's previous sibling that matches the given cssRule.

40. previousSiblings()

Collects all of element's previous siblings and returns them as an array of extended elements.

41. readAttribute()

Returns the value of element's attribute or null if attribute has not been specified.

42. recursivelyCollect()

Recursively collects elements whose relationship is specified by property.

43. relativize()

Turns element into an relatively-positioned element without changing its position in the page layout.

44. remove ()

Completely removes element from the document and returns it.

45. removeClassName()

Removes element's CSS className and returns element.

46. replace ()

Replaces element by the content of the html argument and returns the removed element.

47. scrollTo ()

Scrolls the window so that element appears at the top of the viewport. Returns element.

48. select()

Takes an arbitrary number of CSS selectors (strings) and returns an array of extended descendants of element that match any of them.

49. setOpacity()

Sets the visual opacity of an element while working around inconsistencies in various browsers.

50. setStyle()

Modifies element's CSS style properties.

51. show()

Displays and returns element.

52. siblings()

Collects all of element's siblings and returns them as an array of extended elements.

53. stopObserving()

Unregisters handler and returns element.

54. toggle()

Toggles the visibility of element.

55. toggleClassName()

Toggles element's CSS className and returns element.

56. undoClipping()

Sets element's CSS overflow property back to the value it had before Element.makeClipping() was applied. Returns element.

57. undoPositioned()

Sets element back to the state it was before Element.makePositioned was applied to it. Returns element.

58. up()

Returns element's first ancestor that matches the given cssRule.

59. update()

Replaces the content of element with the provided newContent argument and returns element.

60. viewportOffset()

Returns the X/Y coordinates of element relative to the viewport.

61. visible()

Returns a Boolean indicating whether or not element is visible.

62. wrap()

Wraps an element inside another, then returns the wrapper.

63. writeAttribute()

Adds, specifies or removes attributes passed as either a hash or a name/value pair.

Prototype - Number Processing

Prototype extends native JavaScript numbers in order to provide −

  • ObjectRange compatibility, through Number#succ.

  • Ruby-like numerical loops with Number#times.

  • Simple utility methods such as Number#toColorPart and Number#toPaddedString.

Here is the list of all the functions with examples dealing with Numbers.

Prototype Number Method

NOTE − Make sure you have the prototype.js version of 1.6.

S.No. Method & Description
1. abs()

Returns the absolute value of the number.

2. ceil()

Returns the smallest integer greater than or equal to the number.

3. floor()

Returns the largest integer less than or equal to the number.

4. round()

Rounds the number to the nearest integer.

5. succ()

Returns the successor of the current Number, as defined by current + 1. Used to make numbers compatible with ObjectRange.

6. times()

Encapsulates a regular [0..n] loop, Ruby-style.

7. toColorPart()

Produces a 2-digit hexadecimal representation of the number (which is therefore assumed to be in the [0..255] range). Useful for composing CSS color strings.

8. toJSON()

Returns a JSON string.

9. toPaddedString()

Converts the number into a string padded with 0s so that the string's length is at least equal to length.

Prototype - String Processing

Prototype enhances the String object with a series of useful methods ranging from the trivial to the complex.

Here is the list of all the functions with examples dealing with String.

Prototype String Methods

NOTE − Make sure you have the prototype.js version of 1.6.

S.No. Method & Description
1. blank()

Checks if the string is 'blank', meaning either empty or containing only whitespace.

2. camelize()

Converts a string separated by dashes into a camelCase equivalent. For instance, 'foo-bar' would be converted to 'fooBar'.

3. capitalize()

Capitalizes the first letter of a string and downcases all the others.

4. dasherize()

Replaces every instance of the underscore character ("_") by a dash ("-").

5. empty()

Checks if the string is empty.

6. endsWith()

Checks if the string ends with substring.

7. escapeHTML()

Converts HTML special characters to their entity equivalents.

8. evalJSON()

Evaluates the JSON in the string and returns the resulting object.

9. evalScripts()

Evaluates the content of any script block present in the string. Returns an array containing the value returned by each script.

10. extractScripts()

Extracts the content of any script block present in the string and returns them as an array of strings.

11. gsub()

Returns the string with every occurrence of a given pattern replaced by either a regular string, the returned value of a function or a Template string.

12. include()

Checks if the string contains a substring.

13. inspect()

Returns a debug-oriented version of the string.

14. interpolate()

Treats the string as a Template and fills it with object's properties.

15. isJSON()

Checks if the string is valid JSON by the use of regular expressions. This security method is called internally.

16. parseQuery()

Parses a URI-like query string and returns an object composed of parameter/value pairs.

17. scan()

Allows iterating over every occurrence of the given pattern.

18. startsWith()

Checks if the string starts with substring.

19. strip()

Strips all the leading and trailing whitespace from a string.

20. stripScripts()

Strips a string of anything that looks like an HTML script block.

21. stripTags()

Strips a string of any HTML tag.

22. sub()

Returns a string with the first count occurrences of pattern replaced by either a regular string, the returned value of a function or a Template string.

23. succ()

Used internally by ObjectRange. Converts the last character of the string to the following character in the Unicode alphabet.

24. times()

Concatenates the string count times.

25. toArray()

Splits the string character-by-character and returns an array with the result.

26. toJSON()

Returns a JSON string.

27. toQueryParams()

Parses a URI-like query string and returns an object composed of parameter/value pairs.

28. truncate()

Truncates a string to the given length and appends a suffix to it (indicating that it is only an excerpt).

29. underscore()

Converts a camelized string into a series of words separated by an underscore ("_").

30. unescapeHTML()

Strips tags and converts the entity forms of special HTML characters to their normal form.

31. unfilterJSON ()

Strips comment delimiters around Ajax JSON or JavaScript responses. This security method is called internally.

Prototype - Array Processing

Prototype extends all the native JavaScript arrays with quite a few powerful methods.

This is done in two ways −

  • It mixes in the Enumerable module, which brings a ton of methods in already.

  • It adds quite a few extra methods, which are documented in this section.

Using Iterators

One important support provided by Prototype is that you can use java like iterator in JavaScript. See the difference below −

Traditional way of writing a for loop −

for (var index = 0; index < myArray.length; ++index) {
   var item = myArray[index];
   // Your code working on item here...
}

Now if you are using Prototype, then you can replace the above code as follows −

myArray.each(function(item) {
   // Your code working on item here...
});

Here is the list of all the functions with examples dealing with Array.

Prototype Array Methods

NOTE − Make sure you have the prototype.js version of 1.6.

S.No. Method & Description
1. clear()

Clears the array (makes it empty).

2. clone()

Returns a duplicate of the array, leaving the original array intact.

3. compact()

Returns a new version of the array, without any null/undefined values.

4. each()

Iterates over the array in ascending numerical index order.

5. first()

Returns the first item in the array, or undefined if the array is empty.

6. flatten()

Returns a "flat" (one-dimensional) version of the array.

7. from()

Clones an existing array or creates a new one from an array-like collection.

8. indexOf()

Returns the position of the first occurrence of the argument within the array.

9. inspect()

Returns the debug-oriented string representation of an array.

10. last()

Returns the last item in the array, or undefined if the array is empty.

11. reduce()

Reduces arrays: one-element arrays are turned into their unique element, while multiple-element arrays are returned untouched.

12. reverse()

Returns the reversed version of the array. By default, directly reverses the original. If inline is set to false, uses a clone of the original array.

13. size()

Returns the size of the array.

14. toArray()

This is just a local optimization of the mixed-in toArray from Enumerable.

15. toJSON()

Returns a JSON string.

16. uniq()

Produces a duplicate-free version of an array. If no duplicates are found, the original array is returned.

17. without()

Produces a new version of the array that does not contain any of the specified values.

Prototype - Hash Processing

Hash can be thought of as an associative array binding unique keys to values. Only difference is that you can use any string as an index instead of just using a number as index.

Creating a Hash

There are two ways to construct a Hash instance −

  • Use JavaScript keyword new.
  • Using Prototype Utility function $H.

To create an empty hash you call any of the constructor methods without arguments, too.

Following is the example showing how to create hash, setting values and getting values in a simple way −

// Creating Hash
var myhash = new Hash();
var yourhash = new Hash( {fruit: 'apple'} );
var hishash = $H( {drink: 'pepsi'} );

// Set values in terms of key and values.
myhash.set('name', 'Bob');

// Get value of key 'name' as follows.
myhash.get('name');
yourhash.get('fruit');
hishash.get('drink');

// Unset a key & value
myhash.unset('name');
yourhash.unset('fruit');
hishash.unset('drink');

Prototype provides a wide range of methods to evaluate Hash with ease. This tutorial will explain every method in detail with suitable examples.

Here is a complete list of all the methods related to Hash.

Prototype Hash Methods

NOTE − Make sure at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. clone()

Returns a clone of hash.

2. each()

Iterates over the name/value pairs in the hash.

3. get()

Returns the value of the hash key's property.

4. inspect()

Returns the debug-oriented string representation of the hash.

5. keys()

Provides an Array of keys (that is, property names) for the hash.

6. merge()

Merges object to hash and returns the result of that merge.

7. remove()

Removes keys from a hash and returns their values. This method has been deprecated in version 1.6.

8. set()

Sets the hash key's property to value and returns value.

9. toJSON()

Returns a JSON string.

10. toObject()

Returns a cloned, vanilla object.

11. toQueryString()

Turns a hash into its URL-encoded query string representation.

12. unset()

Deletes the hash key's property and returns its value.

13. update()

Updates hash with the key/value pairs of object. The original hash will be modified.

14. values()

Collects the values of a hash and returns them in an array.

Prototype - Basic Object

Object is used by Prototype as a namespace and to call related function using Object object. This is used in the following two ways −

  • If you are a simple developer, then you can use the existing functions like inspect or clone.

  • If you are one who wishes to create their own objects like Prototype does, or explore objects as if they were hashes, will turn to extend, keys and values.

Prototype Object Methods

NOTE − Make sure at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. clone()

Clones the passed object using shallow copy (copies all the original's properties to the result).

2. extend()

Copies all properties from the source to the destination object.

3. inspect()

Returns the debug-oriented string representation of the object.

4. isArray ()

Returns true if obj is an array, false otherwise.

5. isElement()

Returns true if obj is a DOM node of type 1, false otherwise.

6. isFunction()

Returns true if obj is of type function, false otherwise.

7. isHash()

Returns true if obj is an instance of the Hash class, false otherwise.

8. isNumber()

Returns true if obj is of type number, false otherwise.

9. isString()

Returns true if obj is of type string, false otherwise.

10. isUndefined()

Returns true if obj is of type undefined, false otherwise.

11. keys()

Treats any object as a Hash and fetches the list of its property names.

12. toHTML()

Returns the return value of obj's toHTML method if it exists, else runs obj through String.interpret.

13. toJSON()

Returns a JSON string.

14. toQueryString()

Turns an object into its URL-encoded query string representation.

15. values()

Treats any object as a Hash and fetches the list of its property values.

Prototype - Templating

Templates are used for formatting group of similar objects and to produce formatted output for these objects.

Prototype provides a Template class, which has two methods −

  • Template() − This is a constructor method, which is used to create a template object and call evaluate() method to apply template.

  • evaluate() − This method is used to apply a template to format an object.

There are three steps involved to create the formatted output.

  • Create a template − This involves creating preformatted text. This text contains formatted content along with #{fieldName} values. These #{fieldName} values will be replaced by the actual values when evaluate() method will be called with the actual values.

  • Defining actual values − This involves creating actual values in the form of Keys and Values. These Keys will be mapped in the template and will be replaced by the corresponding values.

  • Mapping Keys and replacing Values − This is the final step where evaluate() will be called and all the keys available in the formatted object will be replaced by the defined values.

Example1

Step 1

Create a template.

var myTemplate = new Template('The \ TV show #{title} was directed by #{author}.');

Step 2

Prepare our set of values, which will be passed in the above object to have a formatted output.

var record1 = {title: 'Metrix', author:'Arun Pandey'};
var record2 = {title: 'Junoon', author:'Manusha'};
var record3 = {title: 'Red Moon', author:'Paul, John'};
var record4 = {title: 'Henai', author:'Robert'};
var records = [record1, record2, record3, record4 ];

Step 3

Final step is filling up all the values in the template and producing final result as follows −

records.each( function(conv) {
   alert( "Formatted Output : " + myTemplate.evaluate(conv) );
});

So, let's put all these three steps together −

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            //  Create template with formatted content and placeholders.
            var myTemplate = new Template('The \ TV show #{title} was directed by #{author}.');
   
            // Create hashes with the required values for placeholders
            var record1 = {title: 'Metrix', author:'Arun Pandey'};
            var record2 = {title: 'Junoon', author:'Manusha'};
            var record3 = {title: 'Red Moon', author:'Paul, John'};
            var record4 = {title: 'Henai', author:'Robert'};
            var records = [record1, record2, record3, record4 ];

            // Now apply template to produce desired formatted output
            records.each( function(conv) {
               alert( "Formatted Output : " + myTemplate.evaluate(conv) );
            });
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>

This will produce the following result −

Output

Prototype - Enumerating

Enumerable class provides a large set of useful methods for enumerations. Enumerations are objects that act as collection of values.

Enumeration methods are mostly used to enumerate arrays and hashes. There are other objects as well like ObjectRange and various DOM- or AJAX-related objects where you can use enumeration methods.

The Context Parameter

Every method of Enumerable that takes an iterator also takes the context object as the next (optional) parameter. The context object is what the iterator is going to be binded to, so the this keyword inside it will point to the object.

var myObject = {};

['foo', 'bar', 'baz'].each(function(name, index) {
   this[name] = index;
}, myObject); // we have specified the context

myObject;

This will produce the following result −

Output

{ foo: 0, bar: 1, baz: 2}

Using it Efficiently

  • When you need to invoke the same method on all the elements, go with invoke() method.

  • When you need to fetch the same property on all the elements, go with pluck() method.

  • The findAll/select methods retrieve all the elements that match a given predicate. Conversely, the reject() method retrieves all the elements that do not match a predicate. In the specific case where you need both the sets, you can avoid looping twice: just use partition() method.

Here is a complete list of all the methods related to Enumerable.

Prototype Enumerable Methods

NOTE − Make sure you at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. all()

Determines whether all the elements are boolean-equivalent to true, either directly or through computation by the provided iterator.

2. any()

Determines whether at least one element is boolean-equivalent to true, either directly or through computation by the provided iterator.

3. collect()

Returns the results of applying the iterator to each element. Aliased as map().

4. detect()

Finds the first element for which the iterator returns true. Aliased by the find() method.

5. each()

It lets you iterate over all the elements in a generic fashion, then returns the Enumerable, thereby allowing chain-calling.

6. eachSlice()

Groups items in chunks based on a given size, with last chunk being possibly smaller.

7. entries()

Alias for the more generic toArray method.

8. find()

Finds the first element for which the iterator returns true. Convenience alias for detect().

9. findAll()

Returns all the elements for which the iterator returned true. Aliased as select().

10. grep()

Returns all the elements that match the filter. If an iterator is provided, it is used to produce the returned value for each selected element.

11. inGroupsOf()

Groups items in fixed-size chunks, using a specific value to fill up the last chunk if necessary.

12. include()

Determines whether a given object is in the Enumerable or not, based on the == comparison operator. Aliased as member().

13. inject()

Incrementally builds a result value based on the successive results of the iterator.

14. invoke()

Optimization for a common use-case of each() or collect(): invoking the same method, with the same potential arguments, for all the elements.

15. map()

Returns the results of applying the iterator to each element. Convenience alias for collect().

16. max()

Returns the maximum element (or element-based computation), or undefined if the enumeration is empty. Elements are either compared directly, or by first applying the iterator and comparing returned values.

17. member()

Determines whether a given object is in the Enumerable or not, based on the == comparison operator. Convenience alias for include().

18. min()

Returns the minimum element (or element-based computation), or undefined if the enumeration is empty. Elements are either compared directly, or by first applying the iterator and comparing returned values.

19. partition()

Partitions the elements in two groups: those regarded as true, and those considered false.

20. pluck()

Optimization for a common use-case of collect(): fetching the same property for all the elements. Returns the property values.

21. reject()

Returns all the elements for which the iterator returned false.

22. select()

Alias for the findAll() method.

23. size()

Returns the size of the enumeration.

24. sortBy()

Provides a custom-sorted view of the elements based on the criteria computed, for each element, by the iterator.

25. toArray()

Returns an Array representation of the enumeration. Aliased as entries().

26. zip()

Zips together (think of the zip on a pair of trousers) 2 + sequences, providing an array of tuples. Each tuple contains one value per original sequence.

Prototype - Event Handling

Event management is one of the biggest challenges to achieve cross-browser scripting. Every browser has different approaches to handle key strokes.

Prototype Framework handles all cross browser compatibility issues and keeps you free from all trouble related to event management.

Prototype Framework provides Event namespace, which is replete with methods, that all take the current event object as an argument, and happily produce the information you're requesting, across all major browsers.

Event namespace also provides a standardized list of key codes you can use with keyboard-related events. The following constants are defined in the namespace −

S.No. Key Constant & Description
1.

KEY_BACKSPACE

Represent back space key.

2.

KEY_TAB

Represent tab key.

3.

KEY_RETURN

Represent return key.

4.

KEY_ESC

Represent esc key.

5.

KEY_LEFT

Represent left key.

6.

KEY_UP

Represent up key.

7.

KEY_RIGHT

Represent right key.

8.

KEY_DOWN

Represent down key.

9.

KEY_DELETE

Represent delete key.

10.

KEY_HOME

Represent home key.

11.

KEY_END

Represent end key.

12.

KEY_PAGEUP

Represent page up key.

13.

KEY_PAGEDOWN

Represent page down key.

How to Handle Events

Before we start, let us see an example of using an event method. This example shows how to capture the DOM element on which the event occurred.

Example

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         // Register event 'click' and associated call back.
         Event.observe(document, 'click', respondToClick);
  
         // Callback function to handle the event.
         function respondToClick(event) {
            var element = event.element();
            alert("Tag Name : " + element.tagName );
         }
      </script>
   </head>

   <body>
      <p id = "note"> Click on any part to see the result.</p>
      <p id = "para">This is paragraph</p>
      <div id = "division">This is divsion.</div>
   </body>
</html>

Output

Here is a complete list of all the methods related to Event. The functions you're most likely to use a lot are observe, element and stop.

Prototype Event Methods

NOTE − Make sure you at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. element()

Returns the DOM element on which the event occurred.

2. extend()

Extends the event with all of the methods contained in Event.Methods.

3. findElement()

Returns the first DOM element with a given tag name, upwards from the one on which the event occurred.

4. isLeftClick()

Determines whether a button-related mouse event was about the "left" (primary, actually) button.

5. observe()

Registers an event handler on a DOM element.

6. pointerX()

Returns the absolute horizontal position for a mouse event.

7. pointerY()

Returns the absolute vertical position for a mouse event.

8. stop()

Stops the event's propagation and prevents its default action from being triggered eventually.

9. stopObserving()

Unregisters an event handler.

10. unloadCache()

Unregisters all event handlers registered through observe. Automatically wired for you. Not available since 1.6.

Prototype - Form Management

Prototype provides an easy way to manage HTML forms. Prototype's Form is a namespace and a module for all things form-related, packed with form manipulation and serialization goodness.

While it holds methods dealing with forms as a whole, its sub module Form.Element deals with specific form controls.

Here is a complete list of all the methods related to Form Element.

Prototype Form Methods

NOTE − Make sure you at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. disable()

Disables the form as whole. Form controls will be visible but uneditable.

2. enable()

Enables a fully or partially disabled form.

3. findFirstElement()

Finds first non-hidden, non-disabled form control.

4. focusFirstElement()

Gives keyboard focus to the first element of the form.

5. getElements()

Returns a collection of all form controls within a form.

6. getInputs()

Returns a collection of all INPUT elements in a form. Use optional type and name arguments to restrict the search on these attributes.

7. request()

A convenience method for serializing and submitting the form via an Ajax.Request to the URL of the form's action attribute. The options parameter is passed to the Ajax.Request instance, allowing to override the HTTP method and to specify additional parameters.

8. reset()

Resets a form to its default values.

9. serialize()

Serialize form data to a string suitable for Ajax requests (default behavior) or, if optional getHash evaluates to true, an object hash where keys are form control names and values are data.

10. serializeElements()

Serialize an array of form elements to a string suitable for Ajax requests (default behavior) or, if optional getHash evaluates to true, an object hash where keys are form control names and values are data.

Prototype and JSON Tutorial

Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

  • JSON is easy for humans to read and write.

  • JSON is easy for machines to parse and generate.

  • JSON is based on a subset of the JavaScript Programming Language.

  • JSON is notably used by APIs all over the web and is a fast alternative to XML in Ajax requests.

  • JSON is a text format that is completely language independent.

Prototype 1.5.1 and later version, features JSON encoding and parsing support.

JSON Encoding

Prototype provides the following methods for encoding −

NOTE − Make sure have at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. Number.toJSON()

Returns a JSON string for the given Number.

2. String.toJSON()

Returns a JSON string for the given String.

3. Array.toJSON()

Returns a JSON string for the given Array.

4. Hash.toJSON()

Returns a JSON string for the given Hash.

5. Date.toJSON()

Converts the date into a JSON string (following the ISO format used by JSON).

6. Object.toJSON()

Returns a JSON string for the given Object.

If you are unsure of the type of data you need to encode, your best bet is to use Object.toJSON so −

var data = {name: 'Violet', occupation: 'character', age: 25 };
Object.toJSON(data);

This will produce the following result −

'{"name": "Violet", "occupation": "character", "age": 25}'

Furthermore, if you are using custom objects, you can set your own toJSON method, which will be used by Object.toJSON. For example −

var Person = Class.create();
Person.prototype = {
   initialize: function(name, age) {
      this.name = name;
      this.age = age;
   },  
   toJSON: function() {
      return ('My name is ' + this.name + 
         ' and I am ' + this.age + ' years old.').toJSON();
   }
};
var john = new Person('John', 49);
Object.toJSON(john);

This will produce the following result −

'"My name is John and I am 49 years old."'

Parsing JSON

In JavaScript, parsing JSON is typically done by evaluating the content of a JSON string. Prototype introduces String.evalJSON to deal with this. For example −

var d='{ "name":"Violet","occupation":"character" }'.evalJSON();
d.name;

This will produce the following result −

"Violet"

Using JSON with Ajax

Using JSON with Ajax is very straightforward. Simply invoke String.evalJSON on the transport's responseText property −

new Ajax.Request('/some_url', {
   method:'get',
   onSuccess: function(transport) {
      var json = transport.responseText.evalJSON();
   }
});

If your data comes from an untrusted source, be sure to sanitize it −

new Ajax.Request('/some_url', {
   method:'get',
   requestHeaders: {Accept: 'application/json'},
   onSuccess: function(transport) {
      var json = transport.responseText.evalJSON(true);
   }
}); 

Prototype and AJAX Tutorial

Introduction to AJAX

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.

For a complete understanding on AJAX, please go through our simple AJAX Tutorial.

Prototype Support for AJAX

Prototype framework enables you to deal with Ajax calls in a very easy and fun way that is also safe (cross-browser). Prototype also deals in a smart way with JavaScript code returned from a server and provides helper classes for polling.

Ajax functionality is contained in the global Ajax object. This object provides all the necessary methods to handle AJAX requests and responses in an easy way.

AJAX Request

Actual requests are made by creating instances of the Ajax.Request() object.

new Ajax.Request('/some_url', { method:'get' });

The first parameter is the URL of the request; the second is the options hash. The method option refers to the HTTP method to be used; default method is POST.

AJAX Response Callbacks

Ajax requests are by default asynchronous, which means you must have callbacks that will handle the data from a response. Callback methods are passed in the options hash when making a request −

new Ajax.Request('/some_url', {
   method:'get',
   onSuccess: function(transport) {
      var response = transport.responseText || "no response text";
      alert("Success! \n\n" + response);
   },
   onFailure: function() { alert('Something went wrong...') }
});

Here, two callbacks are passed in the hash −

  • onSuccess
  • onFailure

Any of the above two call is called accordingly based on the status of the response. The first parameter passed to both is the native xmlHttpRequest object from which you can use its responseText and responseXML properties, respectively.

You can specify both callbacks, one or none - it's up to you. Other available callbacks are −

  • onUninitialized
  • onLoading
  • onLoaded
  • onInteractive
  • onComplete
  • onException

They all match a certain state of the xmlHttpRequest transport, except for onException, which fires when there was an exception while dispatching other callbacks.

NOTE − The onUninitialized, onLoading, onLoaded, and onInteractive callbacks are not implemented consistently by all browsers. In general, it's best to avoid using these.

Prototype AJAX Methods

Ajax object provides all the necessary methods to handle AJAX requests and responses in an easy way. Here is a complete list of all the methods related to AJAX.

NOTE − Make sure you at least have the version 1.6 of prototype.js.

S.No. Method & Description
1. Ajax Options

This is not a method but details all core options shared by all AJAX requesters and callbacks.

2. Ajax.PeriodicalUpdater()

Periodically performs an AJAX request and updates a container's contents based on the response text.

3. Ajax.Request()

Initiates and processes an AJAX request.

4. Ajax.Responders()

A repository of global listeners notified about every step of Prototype-based AJAX requests.

5. Ajax.Response()

The object passed as the first argument of all Ajax requests callbacks.

6. Ajax.Updater()

Performs an AJAX request and updates a container's contents based on the response text.

Prototype - Expressing Range

Prototype Ranges represent an interval of values. The preferred way to obtain a range is to use the $R utility function.

You can create a big range of values using a simple syntax as follows −

$R(1, 10).inspect();

$R('a', 'e').inspect();

This will produce the following result −

['1, 2, 3, 4, 5, 6, 7, 8, 9, 10']

['a', 'b', 'c', 'd', 'e']

The include() Method

This method determines whether the value is included in the range −

Syntax

Range.include(value);

Return Value

If value is included, then returns a true value otherwise false.

Example

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            alert ( "Test 1 : " + $R(1, 10).include(5));
            // Returns true
   
            alert ( "Test 2 : " + $R('a', 'h').include('x'));
            // Returns flase
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>

Output

Prototype - Periodical Execution

Many times it is required to execute a function many times after a certain period of time. For example, you may want to refresh your screen after a given time. Prototype provides a simple mechanism to implement it using PeriodicalExecuter object.

The advantage provided by PeriodicalExecuter is that it shields you against multiple parallel executions of the callback function.

Creating a PeriodicalExecuter

The constructor takes two arguments −

  • The callback function.
  • The interval (in seconds) between executions.

Once launched, a PeriodicalExecuter triggers indefinitely, until the page unloads or the executer is stopped using stop() method.

Example

Following is the example which will pop up a dialogue box after every 5 seconds untill you will stop it by pressing "cancel' button.

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function startExec() {
            new PeriodicalExecuter(function(pe) {
               if (!confirm('Want me to annoy you again later?'))
               pe.stop();
            }, 5);
         }
      </script>
   </head>

   <body>
      <p>Click start button to start periodic executer:</p>
      <br />
      <br />
      <input type = "button" value = "start" onclick = "startExec();"/>
   </body>
</html>

Output

Advertisements