SlideShare una empresa de Scribd logo
1 de 38
Descargar para leer sin conexión
Building interactive
 widgets with YUI


                                  Cyril Doussin
           Yahoo! EU Front-End Summit, Dec 2007
Warnings
                                               Lots of code
/**
                                                               YAHOO.env.ua = function() {
 * Returns the namespace specified and creates it if it doesn't exist
                                                                   var o={
 * <pre>
 * YAHOO.namespace(quot;property.packagequot;);
                                                                       /**
 * YAHOO.namespace(quot;YAHOO.property.packagequot;);
                                                                        * Internet Explorer version number or 0. Example: 6
 * </pre>
                              YAHOO.env.ua = function() {               * @property ie
 * Either of the above would create YAHOO.property, then
                                  var o={                               * @type float
 * YAHOO.property.package
                                                                        */
 *
                                      /**                              ie:0,
 * Be careful when naming packages. Reserved words may work in some browsers
                                       * Internet Explorer version number or 0. Example: 6
 * and not others. For instance, the following will fail in Safari:
                                       * @property ie                  /**
 * <pre>
                                       * @type float                    * Opera version number or 0. Example: 9.2
 * YAHOO.namespace(quot;really.long.nested.namespacequot;);
                                       */                               * @property opera
 * </pre>
                                      ie:0,
 * This fails because quot;longquot; is a future reserved word in ECMAScript * @type float
                                                                        */
 *
                                      /**                              opera:0,
 * @method namespace
                                       * Opera version number or 0. Example: 9.2
 * @static
                                       * @property opera               /**
 * @param {String*} arguments 1-n namespaces to create
                                       * @type float
 * @return {Object} A reference to the last namespace object created * Gecko engine revision number. Will evaluate to 1 if
                                       */                      Gecko
 */
                                      opera:0,                          * is detected but the revision could not be found.
YAHOO.namespace = function() {
                                                               Other browsers
    var a=arguments, o=null, i, j, d;
                                      /**                               * will be 0. Example: 1.8
    for (i=0; i<a.length; i=i+1) {
                                       * Gecko engine revision number. * Will evaluate to 1 if Gecko
                                                                           <pre>
         d=a[i].split(quot;.quot;);
                                       * is detected but the revision could not be found. 1.7.8 browsers
                                                                        * Firefox 1.0.0.4: Other   <-- Reports 1.7
         o=YAHOO;
                                       * will be 0. Example: 1.8        * Firefox 1.5.0.9: 1.8.0.9 <-- Reports 1.8
                                       * <pre>
         // YAHOO is implied, so it is ignored if it is included
         for (j=(d[0] == quot;YAHOOquot;) ? 1 :*0; j<d.length; j=j+1) {
                                          Firefox 1.0.0.4: 1.7.8   <-- Reports 1.7
                                       * Firefox 1.5.0.9: 1.8.0.9 <-- Reports 1.8
             o[d[j]]=o[d[j]] || {};
                                       * Firefox 2.0.0.3: 1.8.1.3 <-- Reports 1.8
                                       * Firefox 3 alpha: 1.9a4    <-- Reports 1.9
Warnings
(probably) Norm incompatible
Warnings
   soz
(some) YUI Goals
• Provide solid foundations:
 • Patch up DOM API
 • Do the hard work for you (CSS layouts,
    browser testing etc.)
• Avoid repeating yourself (reusable
  components)
• Make it simple: consistent design, good
  documentation
Javascript widgets
  • Common need: enhance page
    functionality in an unobtrusive, accessible
    way
• ActiveX Flash Javascript is (most often) the
  appropriate way to do this
• nice to make this reusable on many pages/
  sites
YUI widgets
• Autocomplete   • Logger
• Button         • Menu
• Calendar       • Rich Text Editor
• Color Picker   • Slider
• Container      • TabView
• DataTable      • TreeView
YUI widgets
• Autocomplete   • Logger
• Button         • Menu
• Calendar       • Rich Text Editor
• Color Picker   • Slider
• Container      • TabView
• DataTable      • TreeView
YUI Container
“The Container family of components is
designed to enable developers to create
different kinds of content-containing
modules on the web.”
“Module and Overlay are the most basic
containers, and they can be used directly or
extended to build custom containers.”
YUI Container
                    Module

          Overlay

Tooltip        Panel

               Dialog

            SimpleDialog
YUI Container
                    Module

          Overlay          Your Control

Tooltip        Panel

               Dialog

            SimpleDialog
YAHOO.widget.Module

• Common markup structure
• Customisation through Configuration
• Custom Events
• Utility functions
Our example:
Contact List with pagination
Setting things up:
                Basic Markup
<h2>Contacts</h2>
<ol>
     <li>
         <dl>
             <dt>Name</dt>
             <dd>Ed Eliot</dd>
             <dt>Web site</dt>
             <dd><a href=quot;http://www.ejeliot.com/quot;>ejeliot.com</a></dd>
         </dl>
     </li>
     <li>
         <dl>
             <dt>Name</dt>
             <dd>Stuart Colville</dd>
             <dt>Web site</dt>
             <dd><a href=quot;http://muffinresearch.co.uk/quot;>Muffin Research Labs</a></dd>
         </dl>
     </li>
     <li>
         <dl>
             <dt>Name</dt>
             <dd>Ben Ward</dd>
             <dt>Web site</dt>
             <dd><a href=quot;http://ben-ward.co.uk/quot;>ben-ward.co.uk</a></dd>
         </dl>
     </li>
</ol>
Setting things up:
          Structured Markup
<div id=quot;contact-listquot;>
    <div class=quot;hdquot;>
        <h2>Contacts</h2>
    </div>
    <div class=quot;bdquot;>
        <ol>
            <li>
                 <dl>
                      <dt>Name</dt>
                      <dd>Ed Eliot</dd>
                      <dt>Web site</dt>
                      <dd><a href=quot;http://www.ejeliot.com/quot;>ejeliot.com</a></dd>
                 </dl>
            </li>
            <li>
                 <dl>
                      <dt>Name</dt>
                      <dd>Stuart Colville</dd>
                      <dt>Web site</dt>
                      <dd><a href=quot;http://muffinresearch.co.uk/quot;>Muffin Research Labs</a></dd>
                 </dl>
            </li>
            <li>
                 <!-- ... -->
            </li>
        </ol>
    </div>
    <div class=quot;ftquot;></div>
</div>
Setting things up:
          Structured Markup
<div id=quot;contact-listquot;>
    <div class=quot;hdquot;>
        <h2>Contacts</h2>
    </div>
    <div class=quot;bdquot;>
        <ol>
            <li>
                 <dl>
                      <dt>Name</dt>
                      <dd>Ed Eliot</dd>
                      <dt>Web site</dt>
                      <dd><a href=quot;http://www.ejeliot.com/quot;>ejeliot.com</a></dd>
                 </dl>
            </li>
            <li>
                 <dl>
                      <dt>Name</dt>
                      <dd>Stuart Colville</dd>
                      <dt>Web site</dt>
                      <dd><a href=quot;http://muffinresearch.co.uk/quot;>Muffin Research Labs</a></dd>
                 </dl>
            </li>
            <li>
                 <!-- ... -->
            </li>
        </ol>
    </div>
    <div class=quot;ftquot;></div>
</div>
Setting things up:
                        dependencies
   • YAHOO
   • YAHOO.util.Dom
   • YAHOO.util.Event
  <script type=quot;text/javascriptquot; src=quot;http://yui.yahooapis.com/2.4.0/build/yahoo-dom-event/yahoo-dom-event.jsquot;></
  script>




   • YAHOO.widget
   • YAHOO.widget.Module
<script type=quot;text/javascriptquot; src=quot;http://yui.yahooapis.com/2.4.0/build/container/container-min.jsquot;></script>
Setting things up:
   extending Module

YAHOO.namespace(YAHOO.Cyril);




YAHOO.Cyril.ContactList = function(el, userConfig) {

   YAHOO.Cyril.ContactList.superclass.constructor.call(this, el, userConfig);
};
YAHOO.extend(YAHOO.Cyril.ContactList, YAHOO.widget.Module);
Done :)

YAHOO.util.Event.onDOMReady(function() {
    var contact_list = new YAHOO.Cyril.ContactList('contact-list');
});




YAHOO.util.Event.onDOMReady(function() {
    var contact_list = new YAHOO.Cyril.ContactList('contact-list');
    YAHOO.util.Dom.batch(
        [ contact_list.element, contact_list.header, contact_list.body, contact_list.footer],
        function(el) {
            el.style.border = '1px solid red';
        }
    );
});
Done :)
Configuration
YAHOO.Cyril.ContactList.prototype.initDefaultConfig = function () {

    YAHOO.Cyril.ContactList.superclass.initDefaultConfig.call(this);

    /**
    * Maximum number of contacts to show
    * @config
    * @type Number
    * @default 2
    */
    this.cfg.addProperty('num_contacts', {
        handler: this.configNumContacts,
        validator: this.validateNumContacts,
        suppressEvent: true,
        supercedes: false,
        value: 2
    });
}
Configuration

YAHOO.Cyril.ContactList.prototype.validateNumContacts = function(value) {

     value = parseInt(value);

     return !(isNan(value) || (value < 1) || (value > 3));

};
Configuration


contact_list.config.setProperty('num_contacts', 1);

alert(contact_list.getProperty('num_contacts));
Custom Events
Custom Events
Custom Events

A structured way to make your Control play well:


   • with other Controls
   • with itself
Custom Events
/**
* Initializes the custom events for YAHOO.Cyril.ContactList.
* This method gets called by YAHOO.widget.Module.prototype.init
* @method initEvents
*/
YAHOO.Cyril.ContactList.prototype.initEvents = function() {

     // call the base class method to make sure inherited custom events get set up

    YAHOO.Cyril.ContactList.superclass.initEvents.call(this);


    /**

    * CustomEvent fired before showing a different contact

    * @event beforeUpdateContactsEvent

    * @param {HTMLElement} contactElement LI HTMLElement for the contact to show

    */

    this.beforeUpdateContactsEvent = new YAHOO.util.CustomEvent(quot;beforeShowContactquot;, this);


    /**

    * CustomEvent fired after showing a different contact

    * @event updateContactsEvent

    * @param {HTMLElement} contactElement LI HTMLElement for the contact now displayed

    */

    this.updateContactsEvent = new YAHOO.util.CustomEvent(quot;showContactquot;, this);
};
Custom Events
 giving control to third-party code


contact_list.updateContactsEvent.subscribe(function(type, args) {
    alert(args[0].current_index);
});




var contactElement = get a reference to the new contact element here;
if (this.beforeUpdateContactsEvent.fire(contactElement)) {
    // ... change the contact displayed to contactElement here
}
this.updateContactsEvent.fire(contactElement);
Init function

• called upon instantiation
• some “mandatory” things to do
• gets your widget up and running
Init function

Call YAHOO.widget.Module.prototype.init

   YAHOO.Cyril.ContactList.superclass.init.call(this, el/*, userConfig*/);
Init function

Fire quot;beforeInitquot; and quot;initquot; events when appropriate
        this.beforeInitEvent.fire(YAHOO.Cyril.ContactList);

        // .. rest of the init function

        this.initEvent.fire(YAHOO.Cyril.ContactList);




    Note there is no need to call this.initEvents(...) to
                initialise Custom Events
Init function

                 Cache DOM references

      // cache element reference

      this.some_element = document.getElementById('some_element_id');




No need for the main widget’s element + header, body,
             and footer child elements.
Init function

   Do DOM manipulations

// create/modify DOM elements (ie. previous/next links)

this.initDOMManipulations();
Init function

      set up Event listeners

// initialise event delegation

this.initEventListeners();
Init function

         Default behaviour

// show/hide contact elements

this.updateDisplay();
Init function
YAHOO.Cyril.ContactList.prototype.init = function(el, userConfig) {

          // Note that we don't pass the user config in here yet because we only want it processed once, at
the lowest subclass level (by calling this.cfg.applyConfig later on)
          // this also calls this.initEvents
        
YAHOO.Cyril.ContactList.superclass.init.call(this, el/*, userConfig*/);
        
        
// fire event saying we are about to start the initialisation
        
this.beforeInitEvent.fire(YAHOO.Cyril.ContactList);
        
        
if (userConfig) {
        

    this.cfg.applyConfig(userConfig, true);
        
}
        
        
this.contact_elements = this.body.getElementsByTagName('li');
        
if (this.contact_elements.length == 0) {
        
     return;
        
}
        
this.current_index = 0;

            // create/modify DOM elements (ie. previous/next links)
            this.initDOMManipulations();
            // show/hide contact elements
            this.updateDisplay();
            // initialise event delegation
            this.initEventListeners();

        
// fire event saying initialisation of the Control is done
        
this.initEvent.fire(YAHOO.Cyril.ContactList);
        };
Multiple instances
• store instance in an Array
• Custom Events don’t get in the way
   YAHOO.util.Event.onDOMReady(function() {

         // grab all contact lists by their classes and instanciate them.

         var contact_lists = YAHOO.util.Dom.getElementsByClassName('contact-list');

         for (var i = 0, contact_list; contact_list = contact_lists[i]; i ++) {
             var control = new YAHOO.Cyril.ContactList(contact_list);
             // store a reference to the instance
             YAHOO.Cyril.contactLists = [ control ]
             control.updateContactsEvent.subscribe(function(type, args) {
                 alert('Current index: ' + args[0].current_index);
             });
         }

   });
Teh End
    Cyril Doussin (http://cyril.doussin.name)

    YUI: http://developer.yahoo.com/yui/

    YUI blog: http://yuiblog.com


•   http://www.wat.tv/playlist/689334
•   http://www.jaunted.com/files/3873/French_baguette.jpg
•   http://flickr.com/photos/plasticbag/971055811/
•   http://flickr.com/photos/intranation/1113203816/
•   http://flickr.com/photos/intranation/1870271315/

Más contenido relacionado

La actualidad más candente

Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.fRui Apps
 
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Francois Marier
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentationguestcf600a
 
What makes a good bug report?
What makes a good bug report?What makes a good bug report?
What makes a good bug report?Rahul Premraj
 
HTML 5: The Future of the Web
HTML 5: The Future of the WebHTML 5: The Future of the Web
HTML 5: The Future of the WebTim Wright
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
OOCSS for JavaScript Pirates jQcon Boston
OOCSS for JavaScript Pirates jQcon BostonOOCSS for JavaScript Pirates jQcon Boston
OOCSS for JavaScript Pirates jQcon BostonJohn Hann
 
Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)Christopher Bennage
 
Yii - Next level PHP Framework von Florian Facker
Yii - Next level PHP Framework von Florian FackerYii - Next level PHP Framework von Florian Facker
Yii - Next level PHP Framework von Florian FackerMayflower GmbH
 
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드영욱 김
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016Colin O'Dell
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 

La actualidad más candente (18)

Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
 
Sequelize
SequelizeSequelize
Sequelize
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
What makes a good bug report?
What makes a good bug report?What makes a good bug report?
What makes a good bug report?
 
HTML 5: The Future of the Web
HTML 5: The Future of the WebHTML 5: The Future of the Web
HTML 5: The Future of the Web
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
03DOM.ppt
03DOM.ppt03DOM.ppt
03DOM.ppt
 
Web2py
Web2pyWeb2py
Web2py
 
OOCSS for JavaScript Pirates jQcon Boston
OOCSS for JavaScript Pirates jQcon BostonOOCSS for JavaScript Pirates jQcon Boston
OOCSS for JavaScript Pirates jQcon Boston
 
Introduction to jOOQ
Introduction to jOOQIntroduction to jOOQ
Introduction to jOOQ
 
Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)
 
Yii - Next level PHP Framework von Florian Facker
Yii - Next level PHP Framework von Florian FackerYii - Next level PHP Framework von Florian Facker
Yii - Next level PHP Framework von Florian Facker
 
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
 
Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016Hacking Your Way To Better Security - php[tek] 2016
Hacking Your Way To Better Security - php[tek] 2016
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 

Destacado

Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014
Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014
Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014Grigory Sapunov
 
Введение в архитектуры нейронных сетей / HighLoad++ 2016
Введение в архитектуры нейронных сетей / HighLoad++ 2016Введение в архитектуры нейронных сетей / HighLoad++ 2016
Введение в архитектуры нейронных сетей / HighLoad++ 2016Grigory Sapunov
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Computer Vision and Deep Learning
Computer Vision and Deep LearningComputer Vision and Deep Learning
Computer Vision and Deep LearningGrigory Sapunov
 
Deep Learning Cases: Text and Image Processing
Deep Learning Cases: Text and Image ProcessingDeep Learning Cases: Text and Image Processing
Deep Learning Cases: Text and Image ProcessingGrigory Sapunov
 
Artificial Intelligence - Past, Present and Future
Artificial Intelligence - Past, Present and FutureArtificial Intelligence - Past, Present and Future
Artificial Intelligence - Past, Present and FutureGrigory Sapunov
 
Deep Learning - The Past, Present and Future of Artificial Intelligence
Deep Learning - The Past, Present and Future of Artificial IntelligenceDeep Learning - The Past, Present and Future of Artificial Intelligence
Deep Learning - The Past, Present and Future of Artificial IntelligenceLukas Masuch
 
Deep Learning and the state of AI / 2016
Deep Learning and the state of AI / 2016Deep Learning and the state of AI / 2016
Deep Learning and the state of AI / 2016Grigory Sapunov
 
Deep Learning Computer Build
Deep Learning Computer BuildDeep Learning Computer Build
Deep Learning Computer BuildPetteriTeikariPhD
 
[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習
[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習
[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習台灣資料科學年會
 

Destacado (13)

Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014
Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014
Mooc'и для биологов — Обзор полезных онлайн-курсов / Future Biotech 27.01.2014
 
Apache Spark & MLlib
Apache Spark & MLlibApache Spark & MLlib
Apache Spark & MLlib
 
EdCrunch
EdCrunchEdCrunch
EdCrunch
 
Введение в архитектуры нейронных сетей / HighLoad++ 2016
Введение в архитектуры нейронных сетей / HighLoad++ 2016Введение в архитектуры нейронных сетей / HighLoad++ 2016
Введение в архитектуры нейронных сетей / HighLoad++ 2016
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Computer Vision and Deep Learning
Computer Vision and Deep LearningComputer Vision and Deep Learning
Computer Vision and Deep Learning
 
Multidimensional RNN
Multidimensional RNNMultidimensional RNN
Multidimensional RNN
 
Deep Learning Cases: Text and Image Processing
Deep Learning Cases: Text and Image ProcessingDeep Learning Cases: Text and Image Processing
Deep Learning Cases: Text and Image Processing
 
Artificial Intelligence - Past, Present and Future
Artificial Intelligence - Past, Present and FutureArtificial Intelligence - Past, Present and Future
Artificial Intelligence - Past, Present and Future
 
Deep Learning - The Past, Present and Future of Artificial Intelligence
Deep Learning - The Past, Present and Future of Artificial IntelligenceDeep Learning - The Past, Present and Future of Artificial Intelligence
Deep Learning - The Past, Present and Future of Artificial Intelligence
 
Deep Learning and the state of AI / 2016
Deep Learning and the state of AI / 2016Deep Learning and the state of AI / 2016
Deep Learning and the state of AI / 2016
 
Deep Learning Computer Build
Deep Learning Computer BuildDeep Learning Computer Build
Deep Learning Computer Build
 
[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習
[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習
[DSC 2016] 系列活動:李宏毅 / 一天搞懂深度學習
 

Similar a Custom YUI Widgets

Introduction Dojo Toolkit & IBM Lotus Domino
Introduction Dojo Toolkit & IBM Lotus DominoIntroduction Dojo Toolkit & IBM Lotus Domino
Introduction Dojo Toolkit & IBM Lotus DominoRolf Kremer
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build Systemklipstein
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the CloudJames Thomas
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
Prairie Dev Con West - 2012-03-14 - Webmatrix, see what the matrix can do fo...
Prairie Dev Con West -  2012-03-14 - Webmatrix, see what the matrix can do fo...Prairie Dev Con West -  2012-03-14 - Webmatrix, see what the matrix can do fo...
Prairie Dev Con West - 2012-03-14 - Webmatrix, see what the matrix can do fo...Frédéric Harper
 
Dojo: Getting Started Today
Dojo: Getting Started TodayDojo: Getting Started Today
Dojo: Getting Started TodayGabriel Hamilton
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Christos Manios
 
Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...
Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...
Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...Peter Martin
 
How to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensionsHow to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensionsChristian Trabold
 
Xml Java
Xml JavaXml Java
Xml Javacbee48
 
Basic testing with selenium
Basic testing with seleniumBasic testing with selenium
Basic testing with seleniumSøren Lund
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web TechnologiesPerttu Myry
 

Similar a Custom YUI Widgets (20)

Introduction Dojo Toolkit & IBM Lotus Domino
Introduction Dojo Toolkit & IBM Lotus DominoIntroduction Dojo Toolkit & IBM Lotus Domino
Introduction Dojo Toolkit & IBM Lotus Domino
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build System
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the Cloud
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Trimming The Cruft
Trimming The CruftTrimming The Cruft
Trimming The Cruft
 
Prairie Dev Con West - 2012-03-14 - Webmatrix, see what the matrix can do fo...
Prairie Dev Con West -  2012-03-14 - Webmatrix, see what the matrix can do fo...Prairie Dev Con West -  2012-03-14 - Webmatrix, see what the matrix can do fo...
Prairie Dev Con West - 2012-03-14 - Webmatrix, see what the matrix can do fo...
 
Dojo: Getting Started Today
Dojo: Getting Started TodayDojo: Getting Started Today
Dojo: Getting Started Today
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
Code Documentation. That ugly thing...
Code Documentation. That ugly thing...Code Documentation. That ugly thing...
Code Documentation. That ugly thing...
 
Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...
Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...
Developing a Joomla 3.x Component using RAD FOF- Part 2: Front-end + demo - J...
 
jQuery
jQueryjQuery
jQuery
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
How to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensionsHow to improve the quality of your TYPO3 extensions
How to improve the quality of your TYPO3 extensions
 
Test02
Test02Test02
Test02
 
Xml Java
Xml JavaXml Java
Xml Java
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Basic testing with selenium
Basic testing with seleniumBasic testing with selenium
Basic testing with selenium
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 

Último

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Último (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

Custom YUI Widgets

  • 1. Building interactive widgets with YUI Cyril Doussin Yahoo! EU Front-End Summit, Dec 2007
  • 2. Warnings Lots of code /** YAHOO.env.ua = function() { * Returns the namespace specified and creates it if it doesn't exist var o={ * <pre> * YAHOO.namespace(quot;property.packagequot;); /** * YAHOO.namespace(quot;YAHOO.property.packagequot;); * Internet Explorer version number or 0. Example: 6 * </pre> YAHOO.env.ua = function() { * @property ie * Either of the above would create YAHOO.property, then var o={ * @type float * YAHOO.property.package */ * /** ie:0, * Be careful when naming packages. Reserved words may work in some browsers * Internet Explorer version number or 0. Example: 6 * and not others. For instance, the following will fail in Safari: * @property ie /** * <pre> * @type float * Opera version number or 0. Example: 9.2 * YAHOO.namespace(quot;really.long.nested.namespacequot;); */ * @property opera * </pre> ie:0, * This fails because quot;longquot; is a future reserved word in ECMAScript * @type float */ * /** opera:0, * @method namespace * Opera version number or 0. Example: 9.2 * @static * @property opera /** * @param {String*} arguments 1-n namespaces to create * @type float * @return {Object} A reference to the last namespace object created * Gecko engine revision number. Will evaluate to 1 if */ Gecko */ opera:0, * is detected but the revision could not be found. YAHOO.namespace = function() { Other browsers var a=arguments, o=null, i, j, d; /** * will be 0. Example: 1.8 for (i=0; i<a.length; i=i+1) { * Gecko engine revision number. * Will evaluate to 1 if Gecko <pre> d=a[i].split(quot;.quot;); * is detected but the revision could not be found. 1.7.8 browsers * Firefox 1.0.0.4: Other <-- Reports 1.7 o=YAHOO; * will be 0. Example: 1.8 * Firefox 1.5.0.9: 1.8.0.9 <-- Reports 1.8 * <pre> // YAHOO is implied, so it is ignored if it is included for (j=(d[0] == quot;YAHOOquot;) ? 1 :*0; j<d.length; j=j+1) { Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- Reports 1.8 o[d[j]]=o[d[j]] || {}; * Firefox 2.0.0.3: 1.8.1.3 <-- Reports 1.8 * Firefox 3 alpha: 1.9a4 <-- Reports 1.9
  • 4. Warnings soz
  • 5. (some) YUI Goals • Provide solid foundations: • Patch up DOM API • Do the hard work for you (CSS layouts, browser testing etc.) • Avoid repeating yourself (reusable components) • Make it simple: consistent design, good documentation
  • 6. Javascript widgets • Common need: enhance page functionality in an unobtrusive, accessible way • ActiveX Flash Javascript is (most often) the appropriate way to do this • nice to make this reusable on many pages/ sites
  • 7. YUI widgets • Autocomplete • Logger • Button • Menu • Calendar • Rich Text Editor • Color Picker • Slider • Container • TabView • DataTable • TreeView
  • 8. YUI widgets • Autocomplete • Logger • Button • Menu • Calendar • Rich Text Editor • Color Picker • Slider • Container • TabView • DataTable • TreeView
  • 9. YUI Container “The Container family of components is designed to enable developers to create different kinds of content-containing modules on the web.” “Module and Overlay are the most basic containers, and they can be used directly or extended to build custom containers.”
  • 10. YUI Container Module Overlay Tooltip Panel Dialog SimpleDialog
  • 11. YUI Container Module Overlay Your Control Tooltip Panel Dialog SimpleDialog
  • 12. YAHOO.widget.Module • Common markup structure • Customisation through Configuration • Custom Events • Utility functions
  • 13. Our example: Contact List with pagination
  • 14. Setting things up: Basic Markup <h2>Contacts</h2> <ol> <li> <dl> <dt>Name</dt> <dd>Ed Eliot</dd> <dt>Web site</dt> <dd><a href=quot;http://www.ejeliot.com/quot;>ejeliot.com</a></dd> </dl> </li> <li> <dl> <dt>Name</dt> <dd>Stuart Colville</dd> <dt>Web site</dt> <dd><a href=quot;http://muffinresearch.co.uk/quot;>Muffin Research Labs</a></dd> </dl> </li> <li> <dl> <dt>Name</dt> <dd>Ben Ward</dd> <dt>Web site</dt> <dd><a href=quot;http://ben-ward.co.uk/quot;>ben-ward.co.uk</a></dd> </dl> </li> </ol>
  • 15. Setting things up: Structured Markup <div id=quot;contact-listquot;> <div class=quot;hdquot;> <h2>Contacts</h2> </div> <div class=quot;bdquot;> <ol> <li> <dl> <dt>Name</dt> <dd>Ed Eliot</dd> <dt>Web site</dt> <dd><a href=quot;http://www.ejeliot.com/quot;>ejeliot.com</a></dd> </dl> </li> <li> <dl> <dt>Name</dt> <dd>Stuart Colville</dd> <dt>Web site</dt> <dd><a href=quot;http://muffinresearch.co.uk/quot;>Muffin Research Labs</a></dd> </dl> </li> <li> <!-- ... --> </li> </ol> </div> <div class=quot;ftquot;></div> </div>
  • 16. Setting things up: Structured Markup <div id=quot;contact-listquot;> <div class=quot;hdquot;> <h2>Contacts</h2> </div> <div class=quot;bdquot;> <ol> <li> <dl> <dt>Name</dt> <dd>Ed Eliot</dd> <dt>Web site</dt> <dd><a href=quot;http://www.ejeliot.com/quot;>ejeliot.com</a></dd> </dl> </li> <li> <dl> <dt>Name</dt> <dd>Stuart Colville</dd> <dt>Web site</dt> <dd><a href=quot;http://muffinresearch.co.uk/quot;>Muffin Research Labs</a></dd> </dl> </li> <li> <!-- ... --> </li> </ol> </div> <div class=quot;ftquot;></div> </div>
  • 17. Setting things up: dependencies • YAHOO • YAHOO.util.Dom • YAHOO.util.Event <script type=quot;text/javascriptquot; src=quot;http://yui.yahooapis.com/2.4.0/build/yahoo-dom-event/yahoo-dom-event.jsquot;></ script> • YAHOO.widget • YAHOO.widget.Module <script type=quot;text/javascriptquot; src=quot;http://yui.yahooapis.com/2.4.0/build/container/container-min.jsquot;></script>
  • 18. Setting things up: extending Module YAHOO.namespace(YAHOO.Cyril); YAHOO.Cyril.ContactList = function(el, userConfig) { YAHOO.Cyril.ContactList.superclass.constructor.call(this, el, userConfig); }; YAHOO.extend(YAHOO.Cyril.ContactList, YAHOO.widget.Module);
  • 19. Done :) YAHOO.util.Event.onDOMReady(function() { var contact_list = new YAHOO.Cyril.ContactList('contact-list'); }); YAHOO.util.Event.onDOMReady(function() { var contact_list = new YAHOO.Cyril.ContactList('contact-list'); YAHOO.util.Dom.batch( [ contact_list.element, contact_list.header, contact_list.body, contact_list.footer], function(el) { el.style.border = '1px solid red'; } ); });
  • 21. Configuration YAHOO.Cyril.ContactList.prototype.initDefaultConfig = function () { YAHOO.Cyril.ContactList.superclass.initDefaultConfig.call(this); /** * Maximum number of contacts to show * @config * @type Number * @default 2 */ this.cfg.addProperty('num_contacts', { handler: this.configNumContacts, validator: this.validateNumContacts, suppressEvent: true, supercedes: false, value: 2 }); }
  • 22. Configuration YAHOO.Cyril.ContactList.prototype.validateNumContacts = function(value) { value = parseInt(value); return !(isNan(value) || (value < 1) || (value > 3)); };
  • 26. Custom Events A structured way to make your Control play well: • with other Controls • with itself
  • 27. Custom Events /** * Initializes the custom events for YAHOO.Cyril.ContactList. * This method gets called by YAHOO.widget.Module.prototype.init * @method initEvents */ YAHOO.Cyril.ContactList.prototype.initEvents = function() { // call the base class method to make sure inherited custom events get set up YAHOO.Cyril.ContactList.superclass.initEvents.call(this); /** * CustomEvent fired before showing a different contact * @event beforeUpdateContactsEvent * @param {HTMLElement} contactElement LI HTMLElement for the contact to show */ this.beforeUpdateContactsEvent = new YAHOO.util.CustomEvent(quot;beforeShowContactquot;, this); /** * CustomEvent fired after showing a different contact * @event updateContactsEvent * @param {HTMLElement} contactElement LI HTMLElement for the contact now displayed */ this.updateContactsEvent = new YAHOO.util.CustomEvent(quot;showContactquot;, this); };
  • 28. Custom Events giving control to third-party code contact_list.updateContactsEvent.subscribe(function(type, args) { alert(args[0].current_index); }); var contactElement = get a reference to the new contact element here; if (this.beforeUpdateContactsEvent.fire(contactElement)) { // ... change the contact displayed to contactElement here } this.updateContactsEvent.fire(contactElement);
  • 29. Init function • called upon instantiation • some “mandatory” things to do • gets your widget up and running
  • 30. Init function Call YAHOO.widget.Module.prototype.init YAHOO.Cyril.ContactList.superclass.init.call(this, el/*, userConfig*/);
  • 31. Init function Fire quot;beforeInitquot; and quot;initquot; events when appropriate this.beforeInitEvent.fire(YAHOO.Cyril.ContactList); // .. rest of the init function this.initEvent.fire(YAHOO.Cyril.ContactList); Note there is no need to call this.initEvents(...) to initialise Custom Events
  • 32. Init function Cache DOM references // cache element reference this.some_element = document.getElementById('some_element_id'); No need for the main widget’s element + header, body, and footer child elements.
  • 33. Init function Do DOM manipulations // create/modify DOM elements (ie. previous/next links) this.initDOMManipulations();
  • 34. Init function set up Event listeners // initialise event delegation this.initEventListeners();
  • 35. Init function Default behaviour // show/hide contact elements this.updateDisplay();
  • 36. Init function YAHOO.Cyril.ContactList.prototype.init = function(el, userConfig) { // Note that we don't pass the user config in here yet because we only want it processed once, at the lowest subclass level (by calling this.cfg.applyConfig later on) // this also calls this.initEvents YAHOO.Cyril.ContactList.superclass.init.call(this, el/*, userConfig*/); // fire event saying we are about to start the initialisation this.beforeInitEvent.fire(YAHOO.Cyril.ContactList); if (userConfig) { this.cfg.applyConfig(userConfig, true); } this.contact_elements = this.body.getElementsByTagName('li'); if (this.contact_elements.length == 0) { return; } this.current_index = 0; // create/modify DOM elements (ie. previous/next links) this.initDOMManipulations(); // show/hide contact elements this.updateDisplay(); // initialise event delegation this.initEventListeners(); // fire event saying initialisation of the Control is done this.initEvent.fire(YAHOO.Cyril.ContactList); };
  • 37. Multiple instances • store instance in an Array • Custom Events don’t get in the way YAHOO.util.Event.onDOMReady(function() { // grab all contact lists by their classes and instanciate them. var contact_lists = YAHOO.util.Dom.getElementsByClassName('contact-list'); for (var i = 0, contact_list; contact_list = contact_lists[i]; i ++) { var control = new YAHOO.Cyril.ContactList(contact_list); // store a reference to the instance YAHOO.Cyril.contactLists = [ control ] control.updateContactsEvent.subscribe(function(type, args) { alert('Current index: ' + args[0].current_index); }); } });
  • 38. Teh End Cyril Doussin (http://cyril.doussin.name) YUI: http://developer.yahoo.com/yui/ YUI blog: http://yuiblog.com • http://www.wat.tv/playlist/689334 • http://www.jaunted.com/files/3873/French_baguette.jpg • http://flickr.com/photos/plasticbag/971055811/ • http://flickr.com/photos/intranation/1113203816/ • http://flickr.com/photos/intranation/1870271315/