• Like
Prototype Framework
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Prototype Framework

  • 779 views
Published

 

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
779
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
2
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Julie Iskander, Lecturer at ITIMSc. Communication and Electronics
  • 2. LectureOutlines Object Oriented JavaScript Revision Prototype js Extending the DOM Elements dimensions Event Model Classes and inheritance JSON Ajax
  • 3. OO JavaScript
  • 4. 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
  • 5. Prototype JS
  • 6. Prototype
  • 7. Prototype It is about the abstract not the concrete Many toolkits is built over it like script.aculo.us
  • 8. $ 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 3nodes id=menu and menuitem1 and menuitem2 $ extends node returned with useful prototype nodemethods
  • 9. $$ 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 ofelement with id=menu $$ extends nodes returned with useful prototype nodemethods
  • 10. 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
  • 11. 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);});
  • 12. each Implement continue using return Example:[1,3,4,7,89,6,3,4,5].each(function(elem){if(elem>10)return;alert(elem);});
  • 13. 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);});
  • 14. 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
  • 15. map Applies function on each element, pushes thereturn into an array that is eventually returned Example:[2, 5, 7, 9,50].map(function(item){return item*item;});
  • 16. Extending DOM
  • 17. Prototype’s DOM extensionModifying properties of elementsVisibility .hide() .show() .visible()  returns true/false .toggle()
  • 18. Prototype’s DOM extensionModifying properties of elementsStyle 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’)
  • 19. 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()
  • 20. Templates
  • 21. Templates TheTemplate class uses a basic formatting syntax, similar toRuby. The templates are created from strings that use symbols inthe form (e.g., #{fieldName}) The symbols are replaced by actual values when thetemplate is applied (evaluated) to an object.
  • 22. Examplevar myTemplate =newTemplate(<p>The TV show #{title} was directedby #{author}.</p>);// Create hashes with the required values for placeholdersvar 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};
  • 23. Examplevar records = [record1, record2, record3, record4 ];// Now apply template to produce desired formatted outputrecords.each( function(conv){$$(p)[0].insert( {bottom: "<div>Formatted Output : " +myTemplate.evaluate(conv)+"</div>" });});}
  • 24. Form Management
  • 25. Prototype Form Methods disable() Disables the form as whole. Form controls willbe visible but uneditable. enable() Enables a fully or partially disabled form.
  • 26. Prototype Form Methods findFirstElement() Finds first non-hidden, non-disabledform control. focusFirstElement() Gives keyboard focus to the firstelement of the form. getElements() Returns a collection of all form controlswithin a form.
  • 27. Prototype Form Methods getInputs() Returns a collection of all INPUT elements in aform. Use optional type and name arguments to restrict thesearch on these attributes. request() A convenience method for serializing andsubmitting the form via an Ajax.Request to the URL of theforms action attribute.The options parameter is passed tothe Ajax.Request instance, allowing to override the HTTPmethod and to specify additional parameters. reset() Resets a form to its default values.
  • 28. Element Dimensions
  • 29. Element Dimension Solve problem of inconsistent browsermeasurements .measure(‘ property‘ ) $(‘mydiv’).measure(‘width’)  pixel values For better performance, when measuring more thanone dimension .getLayout()  Layout object $(‘mydiv’).getLayout().get(‘width’); http://prototypejs.org/learn/element-layout
  • 30. Event Model
  • 31. Events A single model for all browsers Event.observe(element,’event’,function{}()) Event.observe(window,’load’,function(){})Element.observe $(‘ ’).observe(‘event’,function(){})
  • 32. Events Can register events on elements or children of anelement. 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(){………………});
  • 33. Event Object All event handlers are receive an event object function submitFun(evnt){evnt.element() //returns element object that triggered eventevnt.preventDefault() //stop default behaviourevnt.isLeftClick() or isRightClick() or isMiddleClick()evnt.pointerX() or pointerY()evnt.pointer()  object{x: , y: }}
  • 34. Classes and Inheritance
  • 35. Class Manages Prototype’s class-based OOP system Class methods: create() Instance Methods: addMethods()
  • 36. Class.create([superclass][, methods...]) superclass (class): superclass to inherit from. method (object): an object (mix-in) that will be mixed-in to mynew class. Multiple mixins can be used, later mixins takeprecedence. returns a constructor function that can be called using newoperator. It will invoke the initialize method. The object mixin must contain ‘initialize’ method to be calledwhen new is called.
  • 37. Class.create()var Person = Class.create({initialize: function(name) { this.name = name; },say: function(message) {return this.name + : + message;}});
  • 38. Example Create your own class that’s mixed withEnumerable
  • 39. Var MyClass=Class.Create(Enumerable, {initialize:function(){………….},_each: function(iterator){for(var i=0;i<……){iterator(….);}}});
  • 40. JSON
  • 41. Encoding Number#toJSON, String#toJSON,Array#toJSON, Hash#toJSON, Date#toJSON, andObject.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.”’
  • 42. Parsing String#evalJSON var data = { "name": "Violet", "occupation": "character"}.evalJSON(); data.name; //-> "Violet”
  • 43. Ajax
  • 44. Ajax A wrapper class around the XMLHttpRequest Uses callbacks to handle different phases of theasynchronous request. If requested page is a JavaScript code then it is automaticallyevaluated and executed.
  • 45. Ajax.Requestnew 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/
  • 46. 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.TopInsertion.BottomInsertion.AfterInsertion.Before
  • 47. Ajax.PeriodicalUpdater Runs Updater in periodical Intervals to repeatedly fetchcontent from the server. new Ajax.PeriodicalUpdater(ID, URL, Options) Same except Options frequency : interval in seconds decay : factor to multiply frequency by everytime the fetchedresponse is the same as the previously fetched. stop() start()
  • 48. References http://prototypejs.org/ Practical Prototype and script.aculo.us, AndrewDupont , 2008