50
Julie Iskander, Lecturer at ITI MSc. Communication and Electronics

Prototype Framework

Embed Size (px)

Citation preview

Page 1: Prototype Framework

Julie Iskander, Lecturer at ITIMSc. Communication and Electronics

Page 2: Prototype Framework

Lectu

re O

utlin

es

Object Oriented JavaScript Revision

Prototype js

Extending the DOM

Elements dimensions

Event Model

Classes and inheritance

JSON

Ajax

Page 3: Prototype Framework

OO JavaScript

Page 4: Prototype Framework

Remember

Everything is an Object

Every Object can have instance methods

All objects have prototype

Functions are first-class Objects

JavaScript is multi-paradigm language Imperative style of C Object oriented style of Java Functional style of Lisp

Page 5: Prototype Framework

First T

heory, then Practice.

Prototype

then

Script.a

culo.us

Page 6: Prototype Framework

Prototype JS

Page 7: Prototype Framework

Prototype

Page 8: Prototype Framework

Prototype

It is about the abstract not the concrete

Many toolkits is built over it like script.aculo.us

Page 9: Prototype Framework

$ Function

$() document.getElementById() $(‘menu’) returns element with id=menu $(element) if element is a node, it is returned

back $(‘menu’,’menuitem1’,’menuitem2’) return an

array of 3 nodes id=menu and menuitem1 and menuitem2

$ extends node returned with useful prototype node methods

Page 10: Prototype Framework

$$ Function

$$(), selects node using CSS selectors, support CSS3 selectors $$(‘li’) select all li elements $$(‘li.current’) select all li elements of

class=current $$(‘#menu a’) select element all a elements inside

of element with id=menu

$$ extends nodes returned with useful prototype node methods

Page 11: Prototype Framework

Enumerable Object

A mixin that provides methods useful for collections

Use in the following classes Array Hash DOM- related objects

Instance Methods: all; any; collect; detect; each; eachSlice; entries;

every; filter; find; find; All; grep; include; inGroupsOf; inject; inspect; invoke; map; max; member; min; partition; pluck; reject; select; size; some; sortBy; toArray; zip

Page 12: Prototype Framework

each

elem.each(Visitor object) Implements visitor on each element Example:

[1,3,4,7,89,6,3,4,5].each(function(elem)

{

alert(elem);

});

Page 13: Prototype Framework

each

Implement continue using return Example:

[1,3,4,7,89,6,3,4,5].each(function(elem)

{

if(elem>10)

return;

alert(elem);

});

Page 14: Prototype Framework

each

Implement break by throw $break Example:

[1,3,4,7,89,6,3,4,5].each(function(elem)

{

if(elem>10)

return;

if(elem==4)

throw $break;

alert(elem);

});

Page 15: Prototype Framework

detect

Takes function that returns true/false

Returns first element that returns true

If no match returns undefined

Examples:[1,3,4,6,8,0,9].detect(function(elem) { return elem==0 }));

See also select, reject, partition

Page 16: Prototype Framework

map

Applies function on each element, pushes the return into an array that is eventually returned

Example:[2, 5, 7, 9,50].map(function(item) { return item*item; });

Page 17: Prototype Framework

Extending DOM

Page 18: Prototype Framework

Prototype’s DOM extension

Modifying properties of elementsVisibility

.hide() .show() .visible() returns true/false .toggle()

Page 19: Prototype Framework

Prototype’s DOM extension

Modifying properties of elementsStyle and classes

.addClassName(‘class name’) .removeClassName(‘class name’) .hasClassName(‘class name’) returns

true/false .toggleClassName(‘class name’) .setStyle({ prop:val,prop:val,……… }) .getStyle(‘css property’)

Page 20: Prototype Framework

Prototype’s DOM extension

Modifying DOM.update(‘ ’)

Change content of element.replace(‘ ’)

Remove element and add a new one in its place

.insert(‘ ’), insert({top:’ ’,bottom:’ ‘, after:’ ‘, before : ‘ ’ })

.remove()

Page 21: Prototype Framework

Templates

Page 22: Prototype Framework

Templates

The Template class uses a basic formatting syntax, similar to Ruby.

The templates are created from strings that use symbols in the form (e.g., #{fieldName})

The symbols are replaced by actual values when the template is applied (evaluated) to an object.

Page 23: Prototype Framework

Example

var myTemplate = new Template('<p>The TV show #{title} was

directed by \ #{author}.</p>');

// 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'};

Page 24: Prototype Framework

Example

var records = [record1, record2, record3, record4 ]; // Now apply template to produce desired formatted output records.each( function(conv) { $$('p')[0].insert( {bottom: "<div>Formatted Output : " + myTemplate.evaluate(conv)+"</div>" }); });}

Page 25: Prototype Framework
Page 26: Prototype Framework

Form Management

Page 27: Prototype Framework

Prototype Form Methods

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

enable() Enables a fully or partially disabled form.

Page 28: Prototype Framework

Prototype Form Methods

findFirstElement() Finds first non-hidden, non-disabled form control.

focusFirstElement()Gives keyboard focus to the first element of the form.

getElements() Returns a collection of all form controls within a form.

Page 29: Prototype Framework

Prototype Form Methods

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

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.

reset() Resets a form to its default values.

Page 30: Prototype Framework

Element Dimensions

Page 31: Prototype Framework

Element Dimension

Solve problem of inconsistent browser measurements

.measure(‘ property‘ )$(‘mydiv’).measure(‘width’) pixel values

For better performance, when measuring more than one dimension .getLayout() Layout object

$(‘mydiv’).getLayout().get(‘width’);

http://prototypejs.org/learn/element-layout

Page 32: Prototype Framework

Event Model

Page 33: Prototype Framework

Events

A single model for all browsers

Event.observe(element,’event’,function{}())Event.observe(window,’load’,function

(){})

Element.observe$(‘ ’).observe(‘event’,function(){})

Page 34: Prototype Framework

Events

Can register events on elements or children of an element.

The selection of children is done using CSS-selectors

Element.on $(‘ ’).on(‘event’,function(){}) $(‘ ’).on(‘event’,’css selector for child’,function()

{})\ $(‘item’).on(‘click’,’li’, function(){

………………

});

Page 35: Prototype Framework

Event Object

All event handlers are receive an event object function submitFun(evnt)

{

evnt.element() //returns element object that triggered event

evnt.preventDefault() //stop default behaviour

evnt.isLeftClick() or isRightClick() or isMiddleClick()

evnt.pointerX() or pointerY()

evnt.pointer() object{x: , y: }

}

Page 36: Prototype Framework

Classes and Inheritance

Page 37: Prototype Framework

Class

Manages Prototype’s class-based OOP system

Class methods: create()

Instance Methods: addMethods()

Page 38: Prototype Framework

Class.create([superclass][, methods...])

superclass (class): superclass to inherit from.

method (object): an object (mix-in) that will be mixed-in to my new class. Multiple mixins can be used, later mixins take precedence.

returns a constructor function that can be called using new operator. It will invoke the initialize method.

The object mixin must contain ‘initialize’ method to be called when new is called.

Page 39: Prototype Framework

Class.create()

var Person = Class.create({

initialize: function(name) { this.name = name; },

say: function(message) { return this.name + ': ' + message;

}

});

Page 40: Prototype Framework

Example

Create your own class that’s mixed with Enumerable

Page 41: Prototype Framework

Var MyClass=Class.Create(Enumerable, {

initialize:function(){………….},

_each: function(iterator){for(var i=0;i<……){

iterator(….);}

}});

Page 42: Prototype Framework

JSON

Page 43: Prototype Framework

Encoding

Number#toJSON, String#toJSON, Array#toJSON, Hash#toJSON, Date#toJSON, and Object.toJSON. var data = {name: 'Violet', occupation: 'character', age: 25 }; Object.toJSON(data); //-> '{"name": "Violet", "occupation": "character", "age": 25}’

For custom objects, Set toJSON method which will be used by Object.toJSON. var Person = Class.create({ initialize: function(name) { this.name = name; }, 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); //-> '"My name is John and I am 49 years old.”’

Page 44: Prototype Framework

Parsing

String#evalJSON var data = '{ "name": "Violet", "occupation":

"character" }'.evalJSON(); data.name; //-> "Violet”

Page 45: Prototype Framework

Ajax

Page 46: Prototype Framework

Ajax

A wrapper class around the XMLHttpRequest

Uses callbacks to handle different phases of the asynchronous request.

If requested page is a JavaScript code then it is automatically evaluated and executed.

Page 47: Prototype Framework

Ajax.Request

new Ajax.Request(URL, Option) URL : string representing the url to request Options hash

method parameters contentType onSuccess onFailure

For complete details: http://api.prototypejs.org/ajax/

Page 48: Prototype Framework

Ajax.Updater

Updates a portion of the DOM with external source

new Ajax.Updater(ID , URL , Options) ID: the id of the element to be updated URL: url to fetch Options: hash same as previous

insertion: Insertion.Top Insertion.Bottom

Insertion.After Insertion.Before

Page 49: Prototype Framework

Ajax.PeriodicalUpdater

Runs Updater in periodical Intervals to repeatedly fetch content from the server.

new Ajax.PeriodicalUpdater(ID, URL, Options) Same except Options

frequency : interval in seconds decay : factor to multiply frequency by everytime the

fetched response is the same as the previously fetched.

stop()

start()

Page 50: Prototype Framework

References

http://prototypejs.org/

Practical Prototype and script.aculo.us, Andrew Dupont , 2008