SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
Hacking With YUI
                               Rajat Pandit (rajat_pandit@ipcmedia.com)




Thursday, September 24, 2009                                              1
YUI Core



Thursday, September 24, 2009              2
Getting Started
                    • Remember the mantra
                           ‘GLOBAL VARIABLES ARE EVIL!!’
                    • Namespace before you start
                               YAHOO.namespace("ipc");
                               YAHOO.ipc.foo = function(o) {
                               
 alert(o);
                               }




Thursday, September 24, 2009                                   3
YAHOO.lang
                    •      Contains utilities functions
                          •    YAHOO.lang.isArray([a,b])

                          •    YAHOO.lang.isBoolean(val)

                          •    YAHOO.lang.isNull(null) // true, false for
                               undefined

                          •    YAHOO.lang.isUndefined(v)

                          •    YAHOO.lang.isFunction(function() {})

                          •    YAHOO.lang.isNumber(o)

                          •    YAHOO.lang.isObject(o)

                          •    YAHOO.lang.isString(s)



Thursday, September 24, 2009                                                4
YAHOO.lang

                    •      YAHOO.lang.hasOwnProperty(o,p)

                           Very useful method to check if the
                           property available in the object is its own
                           or inherited via prototypal inheritance




Thursday, September 24, 2009                                             5
YAHOO.lang
                    • Extending Class is pretty straightforward
                               YAHOO.namespace('ipc'); // namespace
                               YAHOO.ipc.mc = function(info) {
                               
   alert('class: ' + info);
                               }
                               YAHOO.ipc.mc.prototype.testMethod = function(info) {
                               
   alert('class1: ' + info);
                               }

                               // new class
                               YAHOO.ipc.h2h = function(info) {
                               
   YAHOO.ipc.h2h.superclass.constructor.class(this, info);
                               
   alert('class2: ' + info);
                               }

                               // h2h is to extend from mc
                               YAHOO.lang.extend(YAHOO.ipc.h2h, YAHOO.ipc.mc);




Thursday, September 24, 2009                                                                 6
YAHOO.lang
                    • Overriding testMethod in the inherited
                           class and also calling the parent method
                               YAHOO.ipc.h2h.prototype.testMethod = function(info) {
                               
   // chain the method by calling the parent
                               
   YAHOO.ipc.h2h.superclass.testMethod.class(this, info);
                               
   alert('class2: ' + info);
                               };

                               // creating new instance
                               var h2hInstance = new YAHOO.ipc.h2h("constructor");
                               h2hInstance.testMethod("testmethod");




Thursday, September 24, 2009                                                                7
YAHOO.lang
                    • YAHOO.lang.augment allows you to
                           copy properties from one object to
                           another
                           YAHOO.ipc.test1 = function(){};
                           YAHOO.ipc.test1.prototype ={
                           
   foo: 10,
                           
   bar: function() {
                           
   
   console.log('blah');
                           
   }
                           }
                           YAHOO.ipc.test2 = function() {};
                           YAHOO.lang.augment(YAHOO.ipc.test2, YAHOO.ipc.test1);

                           now test2 object has the properties
                           YAHOO.ipc.test2.foo returns 10;




Thursday, September 24, 2009                                                       8
YAHOO.log
                    • Very useful for debugging where firebug
                           doesn’t work
                    • Writing one logging/debugging solution so
                           that it works across all browsers
                               YAHOO.log(‘debug msg’, ‘log level’, ‘class name’)




Thursday, September 24, 2009                                                       9
YAHOO.log
                    • Shameless Plug I



                           http://www.yuiblog.com/blog/2008/07/01/logger-bookmarklet/
                           http://blog.rajatpandit.com/sandbox/yuilogger/index.html




Thursday, September 24, 2009                                                            10
YAHOO.util



Thursday, September 24, 2009                11
YAHOO.util.Region
                    •      Useful API if you are trying to detect if objects are
                           overlapping or intersecting with any other
                           elements.
                    •      Very useful for implementing drag and drop
                           interactions
                               YAHOO.util.Region.contains(region)
                               YAHOO.util.Region.intersect(region)
                               YAHOO.util.Region.union(region)




Thursday, September 24, 2009                                                       12
YAHOO.util.Point
                    • In case you are looking for something more
                           specific like a pixel on the screen
                    • More API details available here
                           http://developer.yahoo.com/yui/docs/
                           module_dom.html



Thursday, September 24, 2009                                       13
YAHOO.util.Dom

                    • Very useful API that allows you to do stuff
                           to the DOM
                    • You can pass an actual node object or its
                           ID, both works




Thursday, September 24, 2009                                        14
YAHOO.util.Dom
                    •      Get positional information for elements
                    •      YAHOO.util.Event.getXY(e) does something similar, tells
                           you where the event happened
                               // get values
                               YAHOO.util.Dom.getXY()
                               YAHOO.util.Dom.getY()
                               YAHOO.util.Dom.getX()

                               // set values
                               YAHOO.util.Dom.setXY()
                               YAHOO.util.Dom.setX()
                               YAHOO.util.Dom.setY()




Thursday, September 24, 2009                                                         15
YAHOO.util.Dom
                    • Modify styles and classes of DOM nodes
                         YAHOO.util.Dom.setStyle(el, '<name>', '<value>');
                         YAHOO.util.Dom.getStyle(el, '<name>');
                         YAHOO.util.Dom.hasClass(el, '<name>');
                         YAHOO.util.Dom.addClass(el, '<name>');
                         YAHOO.util.Dom.removeClass(el, '<class to remove>');
                         YAHOO.util.Dom.replaceClass(el,
                                                     oldclassname,
                                                     newclassname
                         )




Thursday, September 24, 2009                                                    16
YAHOO.util.Dom
                    • Get all nodes with a specified class name
                           starting from a particular node of a
                           particular type
                    •      document.getElementsByClassName(c)
                           Works for Firefox not for IE
                           YAHOO.util.Dom.getElementsByClassName(classname,
                           tagName, rootNode)




Thursday, September 24, 2009                                                  17
YAHOO.util.Dom
                    • Provides the missing DOM API, without
                           messing up the actual objects
                    • Keeps it nice and clean
                               YAHOO.util.Dom.insertAfter(newnode, refNode)
                               YAHOO.util.Dom.isAncestor(haystack, needle)
                               YAHOO.util.Dom.getNextSibling(node)
                               YAHOO.util.Dom.getAncestorByClassName(node,
                               classname)
                               YAHOO.util.Dom.getAncestorByTagName(node, tagname)


                    • More interesting API methods at:
                           http://developer.yahoo.com/yui/docs/


Thursday, September 24, 2009                                                        18
YUI Event

                    • Two components
                     •YAHOO.util.Event
                     •YAHOO.util.CustomEvent


Thursday, September 24, 2009                   19
YAHOO.util.Event
                    •      Basic Event Handling
                    •      Three easy steps
                          •    Define a callback function
                          •    Define the element (get name or actual node)
                          •    Attach callback function to the event
                               YAHOO.util.Event.addListener(‘el’, ‘click’
                               fnCallback)
                               YAHOO.util.Event.addListener(
                                               [el1, el2, el3],
                                               'click',
                                               fnCallBack
                               );

Thursday, September 24, 2009                                                 20
YAHOO.util.Event
                    •      Points to note:
                          •    Attach an event only after the element is available in
                               the DOM, typically after window.onload event
                          •    YUI does the scope correction in the event handler.
                               Provides access to event and currentTarget
                               more consistently
                          •    Also allows you to pass arbitrary object to the
                               handler, the alternate to this is passing values via a)
                               closures b) circular references both complicated
                               ways of doing things.


Thursday, September 24, 2009                                                             21
YAHOO.util.Event
                    • Callback Function Signature
                               function fnCallback(e, obj) {
                               
   // do stuff here
                               }

                               // passes myobj is the second parameter

                               YAHOO.util.Event.addListener(el, 'click', fnCallback,
                               myobj);

                               // if we pass true as the final parameter, the custom
                               // object that is passed is used for the execution scope
                               // (so it becomes 'this' in the callback function)

                               YAHOO.util.Event.addListener(el, 'click', fnCallback,
                               myobj, true);




Thursday, September 24, 2009                                                              22
YAHOO.util.Event
                    • Event handler signature continued...
                    // or pass a totally different mydata = obj
                    // and myobject = this inside the callback function

                    YAHOO.util.Event.addListener(el, 'click', fnCallback,
                    mydata, myobject);




Thursday, September 24, 2009                                                23
Removing Events
                    • Remember IE6 and all its loveliness of
                           memory leaks??
                    • Ensure that you have removed all its
                           listeners before you remove a node in DOM
                               YAHOO.util.Event.removeListener(el, ‘click’, fnCallback)

                               // if reference to the callback function isn’t
                               // available, the following will remove all
                               // listeners
                               YAHOO.util.Event.removeListeners(el, ‘click’)




Thursday, September 24, 2009                                                              24
Removing Events
                    •      To remove all event handlers
                               YAHOO.util.Event.purgeEvent(el)


                    •      To recurse through all children and remove all
                           listeners
                               YAHOO.util.Event.purgeEvent(el, true)


                    •      To remove listeners only for a particular event
                               YAHOO.util.Event.purgeEvent(el, false, ‘click’)




Thursday, September 24, 2009                                                     25
Getting all listeners
                    • You can get the list of all the attached
                           listeners
                      var listeners = YAHOO.util.Event.getListeners(el)

                      // the listener   object has the following structure
                      listener = {
                         type: ‘’, //   the event type
                         fn: ‘’,   //   function to execute, event handler
                         obj: ‘’, //    custom object that was passed
                         adjust: ‘’//   scope correction, this or custom obj
                      }




Thursday, September 24, 2009                                                   26
When to attach handlers?

                    • Do stuff / attach handlers only when you
                           are sure that the DOM is now fully
                           available
                               function init() {
                                   console.log(‘blah’);
                               }
                               YAHOO.util.Event.onDOMReady(init)




Thursday, September 24, 2009                                       27
Custom Events
                    •      They are awesome!!
                    •      You might want to do multiple things when
                           something happens
                    •      One way is to write all the functions invocations
                           one after the other
                    •      Problem happens for AJAX interactions which run
                           in the async. model
                    •      You can create your own custom events, it uses the
                           delegation pattern.


Thursday, September 24, 2009                                                    28
Custom Events
                    •      Shameless Plug II
                           http://blog.rajatpandit.com/2008/02/22/yui-custom-event/
                    •      Three easy steps:
                          •    Step 1: Define the custom event
                                var onMyCustomEvent = new
                                YAHOO.util.CustomEvent(‘onmycustomevent’)
                          •    Step II: Make methods subscribe to the event to be fired, when that
                               happens
                                onMyCustomEvent.subscribe(method1)
                                onMyCustomEvent.subscribe(method2)
                          •    Step III: Fire the event when you think its the right time

                               onMyCustomEvent.fire()




Thursday, September 24, 2009                                                                        29
Custom Events
                    • You can also pass arguments to the
                           subscribed methods when firing the event
                           onMyCustomEvent.fire({action: ‘fire’});

                           function method1(event, arg, obj) {
                           }

                           // event: returns the event object
                           // arg: is the set of arguments passed in the fire event
                           // obj: is the argument that is passed to the subscribe method




Thursday, September 24, 2009                                                                30
YUI Components
                    •      Loads of many hidden gems, widgets etc in the library
                    •      Spend some time at looking at the documentation,
                           tons of examples and API docs


                                    YUI CORE            YUI Library Utilities



                               YUI Controls / Widgets      YUI CSS Tools


Thursday, September 24, 2009                                                       31
References
                    •      YUI Homepage
                           http://developer.yahoo.com/yui/

                    •      YUI Theater for presentations
                           http://developer.yahoo.com/yui/theater/

                    •      API Documentation
                           http://developer.yahoo.com/yui/docs/

                    •      YUI 3 - In beta 1(as on 16th September 2009)
                           http://developer.yahoo.com/yui/3/



Thursday, September 24, 2009                                              32
DEMO



Thursday, September 24, 2009          33

Mais conteúdo relacionado

Destaque

YUI 3: The Most Advance JavaScript Library in the World
YUI 3: The Most Advance JavaScript Library in the WorldYUI 3: The Most Advance JavaScript Library in the World
YUI 3: The Most Advance JavaScript Library in the World
Ara Pehlivanian
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOM
Sukrit Gupta
 

Destaque (20)

Big Data and HPC
Big Data and HPCBig Data and HPC
Big Data and HPC
 
逆向思考
逆向思考逆向思考
逆向思考
 
Hadoop with Lustre WhitePaper
Hadoop with Lustre WhitePaperHadoop with Lustre WhitePaper
Hadoop with Lustre WhitePaper
 
JAXB: Create, Validate XML Message and Edit XML Schema
JAXB: Create, Validate XML Message and Edit XML SchemaJAXB: Create, Validate XML Message and Edit XML Schema
JAXB: Create, Validate XML Message and Edit XML Schema
 
用50元買來的CEO
用50元買來的CEO用50元買來的CEO
用50元買來的CEO
 
自在
自在自在
自在
 
Personal Professional Development
Personal Professional DevelopmentPersonal Professional Development
Personal Professional Development
 
生命是何等美麗 -- 我的好朋友
生命是何等美麗 -- 我的好朋友生命是何等美麗 -- 我的好朋友
生命是何等美麗 -- 我的好朋友
 
YUI 3: The Most Advance JavaScript Library in the World
YUI 3: The Most Advance JavaScript Library in the WorldYUI 3: The Most Advance JavaScript Library in the World
YUI 3: The Most Advance JavaScript Library in the World
 
Building Non-shit APIs with JavaScript
Building Non-shit APIs with JavaScriptBuilding Non-shit APIs with JavaScript
Building Non-shit APIs with JavaScript
 
Java and XML
Java and XMLJava and XML
Java and XML
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
 
Xml processors
Xml processorsXml processors
Xml processors
 
JavaScript Introduction
JavaScript IntroductionJavaScript Introduction
JavaScript Introduction
 
JAXB
JAXBJAXB
JAXB
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOM
 
XML SAX PARSING
XML SAX PARSING XML SAX PARSING
XML SAX PARSING
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
The Mysteries Of JavaScript-Fu (@media Europe Edition)
The Mysteries Of JavaScript-Fu (@media Europe Edition)The Mysteries Of JavaScript-Fu (@media Europe Edition)
The Mysteries Of JavaScript-Fu (@media Europe Edition)
 
Xml And JSON Java
Xml And JSON JavaXml And JSON Java
Xml And JSON Java
 

Semelhante a JavaScript with YUI

Semelhante a JavaScript with YUI (20)

Testable Javascript
Testable JavascriptTestable Javascript
Testable Javascript
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
 
Beautiful Documentation with YUI Doc
Beautiful Documentation with YUI DocBeautiful Documentation with YUI Doc
Beautiful Documentation with YUI Doc
 
yui3 is Sexy - 使用 YUI 3 的 Sexy Part !
yui3 is Sexy - 使用 YUI 3 的 Sexy Part !yui3 is Sexy - 使用 YUI 3 的 Sexy Part !
yui3 is Sexy - 使用 YUI 3 的 Sexy Part !
 
Spock
SpockSpock
Spock
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
 
Geekup Leeds - Why the YUI?
Geekup Leeds - Why the YUI?Geekup Leeds - Why the YUI?
Geekup Leeds - Why the YUI?
 
dojo.things()
dojo.things()dojo.things()
dojo.things()
 
OSGi bootcamp - part 1
OSGi bootcamp - part 1OSGi bootcamp - part 1
OSGi bootcamp - part 1
 
Robotium Tutorial
Robotium TutorialRobotium Tutorial
Robotium Tutorial
 
Testing con spock
Testing con spockTesting con spock
Testing con spock
 
JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)JavaScript Library Overview (Ajax Exp West 2007)
JavaScript Library Overview (Ajax Exp West 2007)
 
Codemotion 2015 spock_workshop
Codemotion 2015 spock_workshopCodemotion 2015 spock_workshop
Codemotion 2015 spock_workshop
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
IoC&Laravel
IoC&LaravelIoC&Laravel
IoC&Laravel
 
Object oriented JavaScript
Object oriented JavaScriptObject oriented JavaScript
Object oriented JavaScript
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

JavaScript with YUI

  • 1. Hacking With YUI Rajat Pandit (rajat_pandit@ipcmedia.com) Thursday, September 24, 2009 1
  • 3. Getting Started • Remember the mantra ‘GLOBAL VARIABLES ARE EVIL!!’ • Namespace before you start YAHOO.namespace("ipc"); YAHOO.ipc.foo = function(o) { alert(o); } Thursday, September 24, 2009 3
  • 4. YAHOO.lang • Contains utilities functions • YAHOO.lang.isArray([a,b]) • YAHOO.lang.isBoolean(val) • YAHOO.lang.isNull(null) // true, false for undefined • YAHOO.lang.isUndefined(v) • YAHOO.lang.isFunction(function() {}) • YAHOO.lang.isNumber(o) • YAHOO.lang.isObject(o) • YAHOO.lang.isString(s) Thursday, September 24, 2009 4
  • 5. YAHOO.lang • YAHOO.lang.hasOwnProperty(o,p) Very useful method to check if the property available in the object is its own or inherited via prototypal inheritance Thursday, September 24, 2009 5
  • 6. YAHOO.lang • Extending Class is pretty straightforward YAHOO.namespace('ipc'); // namespace YAHOO.ipc.mc = function(info) { alert('class: ' + info); } YAHOO.ipc.mc.prototype.testMethod = function(info) { alert('class1: ' + info); } // new class YAHOO.ipc.h2h = function(info) { YAHOO.ipc.h2h.superclass.constructor.class(this, info); alert('class2: ' + info); } // h2h is to extend from mc YAHOO.lang.extend(YAHOO.ipc.h2h, YAHOO.ipc.mc); Thursday, September 24, 2009 6
  • 7. YAHOO.lang • Overriding testMethod in the inherited class and also calling the parent method YAHOO.ipc.h2h.prototype.testMethod = function(info) { // chain the method by calling the parent YAHOO.ipc.h2h.superclass.testMethod.class(this, info); alert('class2: ' + info); }; // creating new instance var h2hInstance = new YAHOO.ipc.h2h("constructor"); h2hInstance.testMethod("testmethod"); Thursday, September 24, 2009 7
  • 8. YAHOO.lang • YAHOO.lang.augment allows you to copy properties from one object to another YAHOO.ipc.test1 = function(){}; YAHOO.ipc.test1.prototype ={ foo: 10, bar: function() { console.log('blah'); } } YAHOO.ipc.test2 = function() {}; YAHOO.lang.augment(YAHOO.ipc.test2, YAHOO.ipc.test1); now test2 object has the properties YAHOO.ipc.test2.foo returns 10; Thursday, September 24, 2009 8
  • 9. YAHOO.log • Very useful for debugging where firebug doesn’t work • Writing one logging/debugging solution so that it works across all browsers YAHOO.log(‘debug msg’, ‘log level’, ‘class name’) Thursday, September 24, 2009 9
  • 10. YAHOO.log • Shameless Plug I http://www.yuiblog.com/blog/2008/07/01/logger-bookmarklet/ http://blog.rajatpandit.com/sandbox/yuilogger/index.html Thursday, September 24, 2009 10
  • 12. YAHOO.util.Region • Useful API if you are trying to detect if objects are overlapping or intersecting with any other elements. • Very useful for implementing drag and drop interactions YAHOO.util.Region.contains(region) YAHOO.util.Region.intersect(region) YAHOO.util.Region.union(region) Thursday, September 24, 2009 12
  • 13. YAHOO.util.Point • In case you are looking for something more specific like a pixel on the screen • More API details available here http://developer.yahoo.com/yui/docs/ module_dom.html Thursday, September 24, 2009 13
  • 14. YAHOO.util.Dom • Very useful API that allows you to do stuff to the DOM • You can pass an actual node object or its ID, both works Thursday, September 24, 2009 14
  • 15. YAHOO.util.Dom • Get positional information for elements • YAHOO.util.Event.getXY(e) does something similar, tells you where the event happened // get values YAHOO.util.Dom.getXY() YAHOO.util.Dom.getY() YAHOO.util.Dom.getX() // set values YAHOO.util.Dom.setXY() YAHOO.util.Dom.setX() YAHOO.util.Dom.setY() Thursday, September 24, 2009 15
  • 16. YAHOO.util.Dom • Modify styles and classes of DOM nodes YAHOO.util.Dom.setStyle(el, '<name>', '<value>'); YAHOO.util.Dom.getStyle(el, '<name>'); YAHOO.util.Dom.hasClass(el, '<name>'); YAHOO.util.Dom.addClass(el, '<name>'); YAHOO.util.Dom.removeClass(el, '<class to remove>'); YAHOO.util.Dom.replaceClass(el, oldclassname, newclassname ) Thursday, September 24, 2009 16
  • 17. YAHOO.util.Dom • Get all nodes with a specified class name starting from a particular node of a particular type • document.getElementsByClassName(c) Works for Firefox not for IE YAHOO.util.Dom.getElementsByClassName(classname, tagName, rootNode) Thursday, September 24, 2009 17
  • 18. YAHOO.util.Dom • Provides the missing DOM API, without messing up the actual objects • Keeps it nice and clean YAHOO.util.Dom.insertAfter(newnode, refNode) YAHOO.util.Dom.isAncestor(haystack, needle) YAHOO.util.Dom.getNextSibling(node) YAHOO.util.Dom.getAncestorByClassName(node, classname) YAHOO.util.Dom.getAncestorByTagName(node, tagname) • More interesting API methods at: http://developer.yahoo.com/yui/docs/ Thursday, September 24, 2009 18
  • 19. YUI Event • Two components •YAHOO.util.Event •YAHOO.util.CustomEvent Thursday, September 24, 2009 19
  • 20. YAHOO.util.Event • Basic Event Handling • Three easy steps • Define a callback function • Define the element (get name or actual node) • Attach callback function to the event YAHOO.util.Event.addListener(‘el’, ‘click’ fnCallback) YAHOO.util.Event.addListener( [el1, el2, el3], 'click', fnCallBack ); Thursday, September 24, 2009 20
  • 21. YAHOO.util.Event • Points to note: • Attach an event only after the element is available in the DOM, typically after window.onload event • YUI does the scope correction in the event handler. Provides access to event and currentTarget more consistently • Also allows you to pass arbitrary object to the handler, the alternate to this is passing values via a) closures b) circular references both complicated ways of doing things. Thursday, September 24, 2009 21
  • 22. YAHOO.util.Event • Callback Function Signature function fnCallback(e, obj) { // do stuff here } // passes myobj is the second parameter YAHOO.util.Event.addListener(el, 'click', fnCallback, myobj); // if we pass true as the final parameter, the custom // object that is passed is used for the execution scope // (so it becomes 'this' in the callback function) YAHOO.util.Event.addListener(el, 'click', fnCallback, myobj, true); Thursday, September 24, 2009 22
  • 23. YAHOO.util.Event • Event handler signature continued... // or pass a totally different mydata = obj // and myobject = this inside the callback function YAHOO.util.Event.addListener(el, 'click', fnCallback, mydata, myobject); Thursday, September 24, 2009 23
  • 24. Removing Events • Remember IE6 and all its loveliness of memory leaks?? • Ensure that you have removed all its listeners before you remove a node in DOM YAHOO.util.Event.removeListener(el, ‘click’, fnCallback) // if reference to the callback function isn’t // available, the following will remove all // listeners YAHOO.util.Event.removeListeners(el, ‘click’) Thursday, September 24, 2009 24
  • 25. Removing Events • To remove all event handlers YAHOO.util.Event.purgeEvent(el) • To recurse through all children and remove all listeners YAHOO.util.Event.purgeEvent(el, true) • To remove listeners only for a particular event YAHOO.util.Event.purgeEvent(el, false, ‘click’) Thursday, September 24, 2009 25
  • 26. Getting all listeners • You can get the list of all the attached listeners var listeners = YAHOO.util.Event.getListeners(el) // the listener object has the following structure listener = { type: ‘’, // the event type fn: ‘’, // function to execute, event handler obj: ‘’, // custom object that was passed adjust: ‘’// scope correction, this or custom obj } Thursday, September 24, 2009 26
  • 27. When to attach handlers? • Do stuff / attach handlers only when you are sure that the DOM is now fully available function init() { console.log(‘blah’); } YAHOO.util.Event.onDOMReady(init) Thursday, September 24, 2009 27
  • 28. Custom Events • They are awesome!! • You might want to do multiple things when something happens • One way is to write all the functions invocations one after the other • Problem happens for AJAX interactions which run in the async. model • You can create your own custom events, it uses the delegation pattern. Thursday, September 24, 2009 28
  • 29. Custom Events • Shameless Plug II http://blog.rajatpandit.com/2008/02/22/yui-custom-event/ • Three easy steps: • Step 1: Define the custom event var onMyCustomEvent = new YAHOO.util.CustomEvent(‘onmycustomevent’) • Step II: Make methods subscribe to the event to be fired, when that happens onMyCustomEvent.subscribe(method1) onMyCustomEvent.subscribe(method2) • Step III: Fire the event when you think its the right time onMyCustomEvent.fire() Thursday, September 24, 2009 29
  • 30. Custom Events • You can also pass arguments to the subscribed methods when firing the event onMyCustomEvent.fire({action: ‘fire’}); function method1(event, arg, obj) { } // event: returns the event object // arg: is the set of arguments passed in the fire event // obj: is the argument that is passed to the subscribe method Thursday, September 24, 2009 30
  • 31. YUI Components • Loads of many hidden gems, widgets etc in the library • Spend some time at looking at the documentation, tons of examples and API docs YUI CORE YUI Library Utilities YUI Controls / Widgets YUI CSS Tools Thursday, September 24, 2009 31
  • 32. References • YUI Homepage http://developer.yahoo.com/yui/ • YUI Theater for presentations http://developer.yahoo.com/yui/theater/ • API Documentation http://developer.yahoo.com/yui/docs/ • YUI 3 - In beta 1(as on 16th September 2009) http://developer.yahoo.com/yui/3/ Thursday, September 24, 2009 32