Friday, August 10, 2007

Notes from Peepcode tutorial on Prototype.js

Notes from Peepcode tutorial on Prototype.js
ver 1.5.1

$H()
$A()

for Hash Object and Array Objects

var smedly = {ape:'brown',frog:'green'}
smedly.ape


var smedly = $H({ape:'brown',frog:'green'})
smedly.keys()

$A isn't really needed...
var asmedly = ['ape','frog','toad']
asmedly.first()

Element.hide('smedly')

$('smedly').hide()

$('smedly').show()

$$('boldTextCSSclass').invoke('hide')

$$('a').invoke('hide')

Anonymous Functions:

$$('a').each(takesAFunction)

$$('a').each(function(element){element.hide()})

Other selector syntaxes (generally uses CSS):
$$('a,p') selects both a's and p's
$$('div p') selects all p's in a div
$$('img') selects all images
$$('img[alt=mephisto-badge]') selects all images with 'mephisto-badge' as alt parm
--------------------------------------------------------

Modules
This is pure JavaScript. Create modules using Hashes.

var myHash = {mykey:myvalue, mykey2:myvalue2}

Now just put function in for the key:value pairs:

var HandyFunctions = {hideLinks: function(){}, showLinks: function(){}}
var HandyFunctions = {
hideLinks: function(){
$$('a').invoke('hide');
},
showLinks: function(){
$$('a').invoke('show')
}
};

Note: when you call these functions, even though they are Hash keys, make sure to put parentheses at end:
HandyFunction.hideLinks()

Classes
Note: see Yahoo video for painfully in-depth exploration of JavaScript classes.
Prototype makes it simpler. Just use Class.create() !!
They are similar to the Module concept above, but with some added functionality:
initialize,
parameters that can be passed to functions,
and you can use "this" keyword.

var Butter = Class.create()
Butter.prototype = {mykey:myvalue}

Butter.prototype = {
initialize: function(brand) {
this.brand = brand;
this.melted = false;
},
melt: function(){
this.melted = true;
}
}

var parkay = new Butter('Parkay');

Extend

addMethods

See Quirksmode for list of cross-browser behaviors (onmousever, onclick, etc)

No comments: