Section 10.3. Core Extensions


10.3. Core Extensions

Prototype's core extensions are methods for working with JavaScript data structures, through new classes and extensions of core classes.

10.3.1. Array Extensions

The $A( object ) method converts object into an array. Combined with the extensions for the Array class, this makes it easier to convert or copy any enumerable list into an array. One suggested use is to convert DOM NodeLists into regular arrays, which can be traversed more efficiently.


clear( )

Empties the array and returns itself.

[1, 2, 3].clear(  ) // => []


compact( )

Returns the array without the elements that are null or undefined. Does not change the array itself.

[1, null, 3].compact(  ) // => [1, 3]


first( )

Returns the first element of the array.

[1, 2, 3].first(  ) // => 1


last( )

Returns the last element of the array.

[1, 2, 3].last(  ) // => 3


flatten( )

Returns a flat, one-dimensional version of the array. Finds each of the array's elements that are also arrays and includes its elements in the returned array, recursively.

[1, [2], 3].flatten(  ) // => [1, 2, 3]


indexOf( value )

Returns the zero-based position of the given value if it is found in the array. Returns -1 if value is not found.

[1, 2, 3].indexOf(1) // => 0


inspect( )

Return a string representation of the array and its elements.

[1, 2, 3].inspect(  ) // => "[1, 2, 3]"


reverse([ inline ])

Returns the array in reverse sequence. If inline is omitted or true, the array itself will also be reversed; otherwise, it remains unchanged.

[1, 2, 3].reverse(  ) // => [3, 2, 1]


shift( )

Returns the first element and removes it from the array, reducing the array's length by 1.

var arr = [1, 2, 3] arr.shift(  ) // => 1 arr.shift(  ) // => 2


without( value1 [, value2 [, ...]])

Returns the array, excluding the elements that are included in the list of arguments.

[1, 2, 3].without(2) // => [1, 3]


reduce( )

If the array only has one element, returns the element. Otherwise, returns the array.

[1, 2, 3].reduce(  ) // => [1, 2, 3] [1].reduce(  ) // => 1


uniq( )

Returns a new array with duplicates removed.

[1, 3, 3].reduce(  ) // => [1, 3]

In addition to the extensions listed here, Array is also extended by the Enumerable methods.

10.3.2. Hashes

The Hash object implements a hash structurea collection of key/value pairs. Each member in a Hash object is an array with two elements: the key and the value, which can be accessed via two properties, key and value. The $H( object ) method adds the Hash methods to object.


keys( )

Returns an array with the keys of all items.

$H({one:'uno',two:'dos'}).keys(  ) // => ["one","two"]


values( )

Returns an array with the values of all items.

$H({one:'uno',two:'dos'}).keys(  ) // => ["uno","dos"]


merge( hash )

Combines the hash with hash and returns the result.

$H({one:'uno',two:'dos'}).merge({two:'2',three:'tres'})  // => #<Hash:{'one': 'uno', 'two': '2', 'three': 'tres'}>


clone( )

Returns a clone of the array.

var a = [1, 2, 3]; var b = a; b.reverse(  ); a; // => [3, 2, 1] var a = [1, 2, 3]; var b = a.clone(  ); b.reverse(  ); a; // => [1, 2, 3]


toQueryString( )

Returns all the items of the hash in a string formatted like a query string.

$H({one:'uno',two:'dos'}).toQueryString(  ) // => "one=uno&two=dos"


inspect( )

Overridden to return a nicely formatted string representation of the hash with its key/value pairs.

$H({one:'uno',two:'dos'}).inspect(  ) // => "#<Hash:{'one': 'uno', 'two': 'dos'}>"

In addition to the extensions listed here, Hash is also extended by the Enumerable methods.

10.3.3. Ranges

An instance of the ObjectRange class represents a range of values, with upper and lower bounds. The $R( start , end , exclusive ) method creates a new ObjectRange instance.


initialize( start , end , exclusive )

Creates a range object, spanning from start to end. It is important to note that start and end have to be objects of the same type and they must have a succ( ) method. If exclusive is true, it includes start and end in the range.


include( searchedValue )

Checks if searchedValue is part of the range. Returns TRue or false.


start

An object of any type representing the lower bound of the range.


end

An object of any type representing the upper bound of the range.


exclusive

A Boolean determining if the boundaries themselves are part of the range.

In addition to the extensions listed here, ObjectRange is also extended by the Enumerable methods.

10.3.3.1. Example
var range = $R(10, 20, false); range.each(function(value, index){   alert(value); });

10.3.4. Enumerable

The Enumerable object contains methods for iterating over collections. The methods are added to other classes, such as Array, Hash, and ObjectRange. Most of the Enumerable methods accept an iterator argumenta function that will be applied to each member of the collection. In all methods, the argument iterator is a function object conforming to Function ( value , index ).


each( iterator )

Calls iterator passing each member in the collection as the first argument and the index of the member as the second argument. Returns the collection.

R(1,5).each(function(n){ alert(n); }); ['Bart', 'Lisa', 'Maggie'].each(function(name, number) { alert(name + " is #" + number); }); // Since the collection is returned, calls can be chained (timers[element] || []).each(clearTimeout).clear(  );


inGroupsOf( number [, fillWith ])

Groups the members into arrays of size number (padding any remainder slots with null or fillWith).

$R(1,6).inGroupsOf(3); // => [[1,2,3],[4,5,6]] $R(1,6).inGroupsOf(4); // => [[1,2,3,4],[5,6,null,null]] $R(1,6).inGroupsOf(4, 'x') // => [[1,2,3,4],[5,6,"x","x"]]


eachSlice( number [, iterator ])

Groups the members into arrays of size number (or less, if number does not divide the collection evenly). If iterator is provided, it's called for each group, and the result is collected and returned.

$R(1,6).eachSlice(3) // => [[1,2,3],[4,5,6]] $R(1,6).eachSlice(4) // => [[1,2,3,4],[5,6]] $R(1,6).eachSlice(3, function(g) { return g.reverse(  ); }) // => [[3,2,1],[6,5,4]]


all([ iterator ])

Returns true if calling iterator for every member evaluates to true (that is, not false or null). If iterator is not given, tests that the member itself is true.

[].all(  ); // => true [true, true, true].all(  ); // => true [true, false, false].all(  ); // => false [false, false, false].all(  ); // => false [1, 2, 3, 4, 5].all(function(n) { return n > 0; }); // => true [1, 2, 3, 4, 5].all(function(n) { return n > 3; }); // => false


any([ iterator ])

Returns true if calling iterator for any member evaluates to true (that is, not false or null). If iterator is not given, tests that the member itself is true.

([].any(  )); // => false [true, true, true].any(  ); // => true [true, false, false].any(  ); // => true [false, false, false].any(  ); // => false [1, 2, 3, 4, 5].any(function(n) { return n > 3; }); // => true [1, 2, 3, 4, 5].any(function(n) { return n > 10; }); // => false


include( obj ) (aliased as member( ) )

Returns TRue if object is found in the collection, false otherwise.

[1, 2, 3].include(3); // => true [1, 2, 3].include(4); // => false


collect( iterator ) (aliased as map( ) )

Calls iterator for each member of the collection and returns each result in an array, one result element for each member of the collection, in the same sequence.

[1,2,3,4].collect(function(n){ return n*n; }) // => [1,4,9,16]


detect( iterator ) (aliased as find( ) )

Calls iterator for each member of the collection and returns the first member that causes iterator to return true. Returns null if no member is found.

// <select > //   <option value="5">Buchanan, Steven</option> //   <option value="8">Callahan, Laura</option> //   <option value="1">Davolio, Nancy</option> // </select> function findEmployeeById(id){ return $$('#employees option').find( function(employee){ return (employee.value == id); }).innerHTML; } findEmployeeById(8); // => "Callahan, Laura"


inject( initialValue , iterator )

Combines all the members of the collection using iterator. Unlike the other Enumerable methods, inject's iterator should conform to Function(accumulator, value, index). In the first iteration, the first argument passed to iterator is initialValue; thereafter it is the result of the previous iteration. Returns the final return value of the last iteration.

$R(1,6).inject(0, function(sum, n){ return sum + n; }); $R(1,4).inject({}, function(memo, n){ memo[n] = n*n; return memo; }); // => {1:1, 2:4, 3:9, 4:16}


select( iterator ) (aliased as findAll( ) )

Calls iterator for each member of the collection and returns an array with all the members that cause iterator to return true. The opposite of reject( ).

$R(1,6).select(function(n){ return n < 4; }); // => [1,2,3]


reject( iterator )

Calls iterator for each member of the collection and returns an array with all the members that cause iterator to return false. The opposite of findAll( )/select( ).

$R(1,6).reject(function(n){ return n < 4; }); // => [4,5,6]


partition([ iterator ])

Returns an array containing two other arrays: the first array containing all the members that evaluate to true (or if given, cause iterator to return true), and the second containing the remaining members.

$R(1,6).partition(function(n){ return n < 4; }); // => [[1,2,3],[4,5,6]]


grep( pattern [, iterator ])

Tests the string value of each member of the collection against pattern (a RegExp object) and returns an array containing all the matching members. If iterator is given, then the array will contain the result of calling iterator with each member that was a match.

['scott','carrie','kevin'].grep(/e/); // => ["carrie","kevin"] ['scott','carrie','kevin'].grep(/e/, function(n){ return n.toUpperCase(  ); }); // => ["CARRIE","KEVIN"]


invoke( methodName [, arg1 [, arg2 [...]]])

Calls the method specified by methodName on each member of the collection, passing any given arguments (arg1 to argN), and returns the results in an array.

[[2, 1, 3], [6, 5, 4]].invoke('sort'); // => [[1,2,3],[4,5,6]]


max([ iterator ])

Returns the member with the greatest value or the greatest result of calling iterator, if iterator is given.

[1,2,3].max(  ); // => 3


min([ iterator ])

Returns the member with the lowest value or the lowest result of calling iterator, if iterator is given.

[1,2,3].min(  ); // => 1


pluck( propertyName )

Retrieves the value of the property or index specified by propertyName in each member of the collection and returns the results in an array.

[{number:2,square:4},{number:3,square:9}].pluck('square'); // [4,9]


sortBy( iterator )

Returns an array with all the members sorted according to the result of the iterator call.

['david','mary'].sortBy(function(name){ return name.length }); // => ["mary","david"]


toArray( ) (aliased as entries( ) )

Returns an array with all the members of the collection.

$R(1,5).toArray(  ); // => [1,2,3,4,5]


zip(collection1[, collection2 [, ... collectionN [, transform ]]])

Merges each given collection with the current collection. The merge operation returns a new array with the same number of elements as the current collection and each element is an array of the elements with the same index from each of the merged collections. If transform is given (a function conforming to Function(value, index)), then each sub-array will be transformed by this function before being returned.

[1,2,3].zip([4,5,6], [7,8,9]) // => [[1,4,7],[2,5,8],[3,6,9]]


inspect( )

Returns a string representation of the enumerable.

$R(1,5).inspect(  ); // => "#<Enumerable:[1, 2, 3, 4, 5]>"

10.3.5. String Extensions


gsub( pattern , replacement )

Returns the result of replacing all occurrences of pattern (either a string or regular expression) with replacement, which can be a string, a function, or a Template string (see "String Templates," later in this chapter). If replacement is a function, it's passed an array of matches. Index 0 of the array contains the entire match; subsequent indexes correspond to parenthesized groups in the pattern.

"In all things will I obey".gsub("all", "ALL"); // => "In ALL things will I obey" "In all things will I obey".gsub(/[aeiou]/i, "_"); // => "_n _ll th_ngs w_ll _ _b_y" "In all things will I obey".gsub(/[aeiou]/i, function(x){ return x[0].toUpperCase(  ); }); // => "In All thIngs wIll I ObEy" 'Sam Stephenson'.gsub(/(\w+) (\w+)/, '#{2}, #{1}'); // => "Stephenson, Sam"


sub( pattern , replacement [, count ])

Identical to gsub( ) but takes an optional third argument specifying the number of matches that will be replaced, defaulting to one.

"In all things will I obey".sub(/[aeiou]/i, "_"); // => "_n all things will I obey" "In all things will I obey".gsub(/[aeiou]/i, "_", 3); // => "_n _ll th_ngs will I obey" 'Sam Stephenson'.sub(/(\w+) (\w+)/, '#{2}, #{1}'); // => "Stephenson, Sam"


scan( pattern , iterator )

Finds all occurrences of pattern and passes each to the function iterator.

// creates two alerts, 'will' and 'obey' "In all things will I obey".scan(/\b\w{4,4}\b/, alert);


truncate( length , truncation )

If the string is longer than length, truncates it and appends truncation, such that the resulting string will be of length length.

"In all things will I obey".truncate(50) // => "In all things will I obey" "In all things will I obey".truncate(9) // => "In all..." "In all things will I obey".truncate(6, '') // => "In all" "In all things will I obey".truncate(14, "... etc.") // => "In all... etc."


strip( )

Returns the string with leading and trailing whitespace removed.

'   hello world  '.strip(  ); // => 'hello world' 'hello world'.strip(  ); // => 'hello world' '  hello  \n  world  '.strip(  ); // 'hello  \n  world' ' '.strip(  ); // => ''


stripTags( )

Returns the string with any HTML or XML tags removed.

'hello world'.stripTags(  ); // => 'hello world' 'hello <span>world</span>'.stripTags(  ); // => 'hello world' '<a href="#" onclick="moo!">hello</a> world'.stripTags(  ); // => 'hello world' 'h<b><em>e</em></b>l<i>l</i>o w<span  ><b>o</b></span>rld'.stripTags(  ); // => 'hello world'


stripScripts( )

Returns the string with any <script /> blocks removed.

'foo bar'.stripScripts(  ); // => 'foo bar' ('foo <script>boo();<'+'/script>bar').stripScripts(  ); // => 'foo bar' ('foo <script type="text/javascript">boo();\nmoo();<'+'/script>bar').stripScripts(  ); // => 'foo bar' ('foo <script>boo();<'+'/script><span>bar</span>').stripScripts(  ); // => 'foo <span>bar</span>'


extractScripts( )

Returns an array containing all the <script /> blocks found in the string.

'foo bar'.extractScripts(  ); // => [] ('foo <script>boo();<'+'/script>bar').extractScripts(); // => ['boo(  );'] ('foo <script>boo();<'+'/script><script>moo();<'+'/script>bar').extractScripts(  ); // => ['boo();','moo(  );']


evalScripts( )

Evaluates each <script /> block found in the string.

var counter = 0; (3).times(function(  ){ ('foo <script>counter++<'+'/script> bar').evalScripts(  ); }); counter; // 3


escapeHTML( )

Returns the string with any HTML markup characters properly escaped.

'foo bar'.escapeHTML(  ); // => 'foo bar' 'foo <span>bar</span>'.escapeHTML(  ); // => 'foo &lt;span&gt;bar&lt;/span&gt;' 'foo &#223; bar'.escapeHTML(  ); // => 'foo &#223; bar'


unescapeHTML( )

Returns the string with any escaped markup unescaped.

'foo bar'.unescapeHTML(  ); // => 'foo bar' 'foo &lt;span&gt;bar&lt;/span&gt;'.unescapeHTML(  ); // 'foo <span>bar</span>' 'foo &#223; bar'.unescapeHTML(  ); // => 'foo &#223; bar'


toQueryParams( ) (aliased as parseQuery( ) )

Returns an object with parameters for each part of a query string.

'a&b=c'.toQueryParams(  )['b']; // => 'c' 'a%20b=c&d=e%20f&g=h'.toQueryParams(  )['d']; // => 'e f'


toArray( )

Splits the string into an array of its characters.

''.toArray(  ); // => [] 'a'.toArray(  ); // => ['a'] 'ab'.toArray(  ); // => ['a','b'] 'foo'.toArray(  ); // => ['f','o','o']


camelize( )

Converts a hyphen-delimited-string into a camelCase string.

'foo'.camelize(  ); // => 'foo' 'foo_bar'.camelize(  ); // => 'foo_bar' 'border-bottom-width'.camelize(  ); // => 'borderBottomWidth'


inspect(useDoubleQuotes)

Returns a quoted representation of the string, useful for debugging. If useDoubleQuotes is true, wraps the string in double quote marks.

''.inspect(  ); // => '\'\'' 'test'.inspect(  ); // => '\'test\'' 'test'.inspect(true); // => '"test"' 'test \'test\' "test"'.inspect(  ); // => '\'test \\\'test\\\' "test"\''

10.3.5.1. String Templates

The Template class provides simple templating functionality with JavaScript strings.


initialize( template [, pattern ])

Creates a new Template instance for the string template. If pattern is given, it overrides the default pattern regular expression, defined in Template.Pattern, which follows Ruby's syntax for variable interpolation.

var row = new Template('<tr><td>#{name}</td><td>#{age}</td></tr>');


evaluate( object )

Renders the template, returning a string with the values of object inserted into the template according to its pattern.

var row = new Template('<tr><td>#{name}</td><td>#{age}</td></tr>'); var person = {name: 'Sam', age: 21}; row.evaluate(person); // => '<tr><td>Sam</td><td>21</td></tr>' row.evaluate({})); // => '<tr><td></td><td></td></tr>' // Using a custom pattern mimicking PHP syntax Template.PhpPattern = /(^|.|\r|\n)(<\?=\s*\$(.*?)\s*\?>)/; var row = new Template('<tr><td><?= $name ?></td><td><?= $age ?></td></tr>', Template.PhpPattern); row.evaluate(person); // "<tr><td>Sam</td><td>21</td></tr>" // <table  border="1"></table> var row = new Template('<tr><td>#{name}</td><td>#{age}</td></tr>'); var people = [{name: 'Sam', age: 21}, {name: 'Marcel', age: 27}]; people.each(function(person){     new Insertion.Bottom('people', row.evaluate(person)); });

10.3.6. Number Extensions


toColorPart( )

Returns the hexadecimal representation of the number. Useful when converting the RGB components of a color into its HTML representation.

(255).toColorPart(  ); // => "ff"


succ( )

Returns the number plus one; useful in scenarios that involve iteration.

(1).succ(  ); // => 2


times( iterator )

Calls iterator (a function object conforming to Function ( index )) n times, passing in values from zero to n-1.

(3).times(alert); // creates 3 alerts for 0, 1, and 2

10.3.7. Events

The Event object provides methods for working with JavaScript events.


observe( element , name , observer , useCapture )

Adds an event handler function observer to element for the event named name (e.g., 'click', 'load', etc.). If useCapture is true, it handles the event in the capture phase, and, if false, it handles it in the bubbling phase.

// Attach an anonymous function to the window.onLoad event. Event.observe(window, 'load', function(e){ alert("Page loaded."); }); // Attach a named function to an element's onClick event. var greet=function(  ) { alert('Hi'); }; Event.observe($('target'), 'click', greet);


stopObserving(element, name, observer, useCapture)

Removes an event handler named name from element. observer is the function that is handling the event. If useCapture is true, it handles the event in the capture phase, and, if false, it handles it in the bubbling phase.

Event.stopObserving($('target'), 'click', greet);


element( event )

Returns element that originated event.

// <div >Click me</div> // <div >Click me 2</div> var greet=function(e) { alert('You clicked ' + Event.element(e).id); }; Event.observe($('target'), 'click', greet); Event.observe($('target2'), 'click', greet);


isLeftClick( event )

Returns true if the left mouse button was clicked.

Event.observe($('target'), 'click', function(e) { if(Event.isLeftClick(e)) alert('You left-clicked.'); });


pointerX( event )

Returns the x coordinate of the mouse pointer on the page.

Event.observe($('target'), 'click', function(e) { alert('You clicked at ' + Event.pointerX(e) + ',' + Event.pointerY(e)); });


pointerY( event )

Returns the y coordinate of the mouse pointer on the page.

Event.observe($('target'), 'click', function(e) { alert('You clicked at ' + Event.pointerX(e) + ',' + Event.pointerY(e)); });


stop( event )

Use this function to abort the default behavior of event and to suspend its propagation.

// <a href="#foo" >Will be stopped</a> // <a href="#bar" >Won't be stopped</a> responder = function(e) { if(Event.element(e).id=='foo') Event.stop(e); } Event.observe($('foo'), 'click', responder); Event.observe($('bar'), 'click', responder);


findElement( event , tagName )

Traverses the DOM tree upwards, searching for the first element named tagName, starting from the element that originated event.

// <div ><a href="#" >foo</a></div> Event.observe($('foo'), 'click', function(e) {     alert(Event.findElement(e, 'div').id); });


observers

Array of cached observers.

Table 10-3 shows the codes and constants for various keys.

Table 10-3. Constants for key codes
ConstantKeyCode
KEY_BACKSPACE

Backspace8
KEY_TAB

Tab9
KEY_RETURN

Return13
KEY_ESC

Escape27
KEY_LEFT

Left arrow37
KEY_UP

Up arrow38
KEY_RIGHT

Right arrow39
KEY_DOWN

Down arrow40
KEY_DELETE

Delete46
KEY_HOME

Home36
KEY_END

End35
KEY_PAGEUP

Page Up33
KEY_PAGEDOWN

Page Down34


10.3.8. Function Extensions


bind( object )

Returns an instance of the function pre-bound to the function(=method) owner object. The returned function will have the same arguments as the original one.


bindAsEventListener( object[, arg1 [...]] )

Returns an instance of the function pre-bound to the function(=method) owner object. The returned function will have the current event object as its argument, plus any additional arguments given.

10.3.8.1. Example
// <input type="checkbox"  value="1"> var CheckboxWatcher = Class.create(  ); CheckboxWatcher.prototype = {   initialize: function(chkBox, message) {     this.chkBox = $(chkBox);     this.message = message;     this.chkBox.onclick =        this.showMessage.bindAsEventListener(this);   },   showMessage: function(evt) {     alert(this.message + ' (' + evt.type + ')');   } }; new CheckboxWatcher('checkbox', 'Changed');

10.3.9. Object Extensions


extend( destination , source )

Copies all properties and methods from source to destination, providing a way to implement inheritance. Returns destination.

destination = {name: "Sam", age: "21"}; source = {name: "Marcel"}; Object.extend(destination, source); destination.name; // "Marcel" // Inline source destination = {name: "Sam", age: "21"}; Object.extend(destination, {name: "Marcel"}).name; // "Marcel" // Provide a default set of options with the capability to override: initialize: function(options) {     this.options = {foo: 'bar'};     Object.extend(this.options, options); }


inspect( targetObj )

Returns a human-readable string representation of targetObj. If targetObj doesn't define an inspect( ) method, defaults to the return value of toString( ).

Object.inspect(  ); // => 'undefined' Object.inspect(undefined); // => 'undefined' Object.inspect(null); // => 'null' Object.inspect('foo\\b\'ar'); // => "'foo\\\\b\\\'ar'" Object.inspect([]); // => '[]'


keys( object )

Returns an array of the names ofobject's properties and methods.

Object.keys({foo:'bar'}); // => ["foo"]


values( object )

Returns an array of the values of object's properties and methods.

Object.values({foo:'bar'}); // => ["bar"]


clone( object )

Returns a shallow clone of objectsuch that the properties of object that are themselves objects are not cloned.

original = {name: "Sam", age: "21", car:{make: "Honda"}}; copy = Object.clone(original); copy.name = "Marcel"; copy.car.make = "Toyota"; original.name; // "Sam" original.car.make; // "Toyota"

10.3.10. Classes

The Class object is used when declaring the other classes in the library. Using this object when declaring a class causes the new class to support an initialize( ) method, which serves as the constructor.


create( )

Defines a constructor for a new class.

var Cow = Class.create(  ); Cow.prototype = {   initialize: function(name) {     this.name = name;   },   vocalize: function(message) {     return this.name + ' says ' + message;   } }; var bessy = new Cow('Bessy'); bessy.vocalize('moo!'); // => 'Bessy says moo!'

10.3.11. PeriodicalExecuter

The PeriodicalExecuter class provides the logic for calling a given function repeatedly, at a given interval.


initialize( callback , interval )

Creates a PeriodicalExecuter instance that will call callback every interval seconds.


callback

The function to be called. No parameters will be passed to it.


frequency

The interval in seconds.


currentlyExecuting

A Boolean indicating whether the function call is in progress.


stop( )

Stops execution.

10.3.11.1. Example
// <div  onclick="toggleClock(  )">Toggle the clock</div> toggleClock = function(  ){   if(typeof executer == 'undefined') {     executer = new PeriodicalExecuter(function(  ){       $('clock').update(new Date(  ));     }, 1);   } else {     executer.stop(  );     executer = undefined;   } };

10.3.12. Try.these( )

Makes it easy to try different function calls until one of them works. Takes any number of functions as arguments and calls them one by one, in sequence, until one of them works, returning the result of that successful function call.

In the example below, the function xmlNode.text works in some browsers, and xmlNode.textContent works in the other browsers. Using the TRy.these( ) function we can return the one that works.

return Try.these(   function(  ) {return xmlNode.text;},   function(  ) {return xmlNode.textContent;} );

10.3.13. Prototype

The Prototype object does not have any important role, other than declaring the version of the library being used.


Version

A string containing the version of the library.

Prototype.Version; // => '1.5.0'


BrowserFeatures

An object used to encapsulate tests for browser capabilities. Currently, the only property of the object is XPath, which evaluates to true if the current browser supports XPath expressions.

if (Prototype.BrowserFeatures.XPath) { alert("You've got XPath"); }


emptyFunction( )

A no-op function; used internally to keep syntax clean; for example, as the default value for a callback.

// Fails gracefully if myFunction is undefined (myFunction || Prototype.emptyFunction)('foo');


K( x )

Prototype's version of the K combinator: returns its first argument, discarding any additional arguments. Used internally to keep syntax clean; for example, as the default value for an iterator.

Prototype.K('foo', 'bar'); // => 'foo'


ScriptFragment

A string describing a regular expression to identify scripts.




Ajax on Rails
Ajax on Rails
ISBN: 0596527446
EAN: 2147483647
Year: 2006
Pages: 103
Authors: Scott Raymond

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net