SlideShare a Scribd company logo
INTRODUCTION TO JAVASCRIPT
AND YOOLKUI
About Me

 var name = “Suylong Khou”;
 var profession = “Javascript Developer”;
 var partTime = “Missionary”;
 var myCore = “Give, and it will be given to
  you. A good measure, pressed down, shaken
  together and running over, will be poured
  into your lap. For with the measure you use, it
  will be measured to you.“.luke(6, 38);
Data Types

   Object
   Function
   Numbers
   Strings
   Booleans
   null - a value that isn’t anything
   undefined - default value for variables and
    parameters, value of missing members in the
    object etc
Objects

 Objects can contain data and methods
 Objects can inherit from other objects
 An object contain an unordered collection of
  name/value pairs
 Values can be any type including other
  objects
 JSON
Object Literals

 Objects are wrapped in {}
 Names can be string
 Value can be an expression
 ; used for separation
 , separate pairs
Object Example

 var myobject = {
       name : “Jack Appleseed”,
       “data”: { foo: 10, bar: 20}
 };
 var data = myobject.data;
 var foo = myobject.data.foo;
typeof Prefix Operator

 The typeof prefix operator returns a
 string identifying the type of value
 Use instanceof instead
Array

 Array inherits from Object (like every other
  object in JavaScript)
 No need to provide length when creating a
  new one
 Unlike object they have a length member and
  is always 1 larger than the highest subscript
Array Methods

 concat
 join (can also be used for concatenating
    multiple strings)
   pop
   push
   slice
   sort
   splice
Checking for Array

• Use construction
    value.constructor === Array
• User instanceof
    value instanceof Array
Function

 They are first class Objects
 Can be passed, stored and returned just like
  any value
 Inherit from object
 Function can appear anywhere an expression
  can appear
Function Cont...

 Functions can be contained inside other
  functions
 Inner function has access to the variable and
  parameters of the function it is contained
  within
 This is static or lexical scoping
 The scope that inner function has access to
  continues even after the parent function has
  returned is called Closure
Closure
function sayHello2(name) {
  var text = 'Hello ' + name; // local variable
  var sayAlert = function() { alert(text); }
  return sayAlert;
}
var say2 = sayHello2(“Foo”);
Say2();
Function Cont...

 Function inside an object is called a method
 When invoked with too many arguments, the
  rest are ignored
 When invoked with fewer arguments,
 the rest are set to undefined
Function’s arguments

 var showMe = function(f00, bar){
     return foo + bar,
 }

 showMe(“foo”, “bar”, “foobar”); //Last
 argument will be ignore
 showMe(“foo”) //bar will be undefined
Function Cont...

 When a function is invoked in method
  format, this refers to the object containing it.
 var foo = {
     baz: 10,
     bar: function() {
       console.log(this.baz);
     }
 };
 foo.bar();
Function Cont...

 When object is invoked in function, this refers
  to the global object

 var global_variable = 5;
 function test() {
       console.log(this.global_variable);
 }
 test();
Function Cont...

 When new Function is used (implicit return is
  optional), then this returns the new object
  created
var Test = function(id) {
      this.something = id;
      this.foo = function() {
            console.log('this is a test: ' +
this.something);
      }
}
var o = new Test(10),
i = new Test(111);
o.foo();
i.foo();
Function (arguments)

 When function is invoked, in addition to its
    parameters it has a special parameter called
    arguments
   Contains all arguments from invocation
   arguments.length will tell you how many
    arguments were passed
   arguments is not of type Array even
   though it has length
Function (arguments)

var foo = function() {
  var a = new Array();
  console.log( typeof a );
  console.log( typeof arguments );
  console.log( arguments instanceof Object );
  console.log( arguments instanceof Array );
}
foo();
(global) Object

 As crockford says, the object that dare not
  speak of its name
 It is the container for all global variables and
  all built in objects
 On browsers window is the global object
 Variables defined with a var makes it local to
  the scope
GLOBAL VARIABLES ARE EVIL

 Un-namespaced values can clash each others
  values
 Use of it should be minimized or gotten rid of
  totally
 Variables defined in the function / module
  should start with var otherwise they have a
  global scope
Object Oriented Javascript
Object-Oriented Basics
 Object (instance): representation of a "thing"
  (someone or something)
 Class - a blueprint, or recipe for an object
 Encapsulation : illustrates the fact that an
  object contains (encapsulates) :
   Data (stored in properties)
   The means to do something with the data (using
    methods)
 Inheritance
Object Creation

 Two simple ways

  var obj = new Object();
  obj.name = “Foo”;
  obj.say = function(){ return “hello”;};


  var obj = {
        name: “Foo”,
        say: function(){
              return “helllo”;
        }
  }
Methods

 When a property is a function we can call it a
  method
          var object = {
             method: function(){
                   alert("here’s method");
             }
          }
prototype

 JavaScript functions work as
  methods, constructors and modules
 It has Prototypal Inheritance, which offers
  great expressive powers
 All objects are directly or indirectly linked to
  Object.prototype
prototype

 Each object is linked to its parent via a magic
  link
 When a member is accessed the compiler
  looks at the object and then looks up to its
  parent via the magic link
 It keeps going all the way up to
  Object.prototype
 Go to console of firebug and type
  Object.prototype
prototype



 Looking for my_object.foo, found it in the object itself
 Looking for my_object.baz looks in the object and if it
  doesn’t find it there it goes to my_object_parent which is
  my_object.prototype
 Looking for my_object.some_random_member can’t
  find it in the object, look at my_object_parent, can’t find
  it
 there either, goes to Object can’t find it there and is set
  to undefined
prototype
var Person = function(){
      this.name = “Mr.Foo”;
      this.callMe = function(){
            alert(“I am “ + this.name );
      }
}
var personObj = new Person();
personObj.callMe();
personObj.constructor();
personObj.myFoo(); //will return undefined
Object Augmentation

  New members can be added to any object

Person.prototype.callMeAgain = function(){
      alert(“I said my name is: “ + this.name);
};
personObj.callMeAgain();
Prototype usage

 callMeAgain() is a property of
 the prototype object

 but it behaves as if it's a
 property of the dude object
Own properties vs. prototype’s

  personObj.hasOwnProperty(“callMe”);
   will return true
  personObj.hasOwnProperty(“callMeAgain”);
   will return false;
isPrototypeOf()
Person.prototype.isPrototypeOf(personObj);
 true
Inheritance

 OOP ensures code reuse
 Two forms of OOP
     Classical with Mixin
     Prototypal
Prototypal Inheritance

var Boy = function(){};
Boy.prototype = new Person();
var boyObj = new Boy();
boyObj.callMe();
Inheritance through Mixin
var Person = function(name){
   this.greet = function(){
      alert("Hello, I'm " + name);
   }
};
var Employee = function(name){
   Person.apply(this, [name]);
   this.getTeam = function(){ return "UI Library";}
}
//instantiate object of Employee
var employee = new Employee("Borey");
employee.greet();

var team = employee.getTeam();
alert("Team: " + team);
Singleton

 There is no need to produce a class-like
  constructor for an object that will have
  exactly one instance
 This is typical of JavaScript applications
 Use an object literal to get started instead
Module Pattern

 The methods of a singleton can enjoy access
  to shared private datum and private methods
 Variables defined in a module are only visible
  in a module
 Variables defined in a function are only visible
  to the function
 Function can be used as module containers
Module Pattern
var my_module = function() {
      var privateVariable,
      privateFunction = function() {
            // stuff
      };
      return {
         firstMethod: function(a,b) {
            // can access privateVariable
            // can access privateFunction
         }
      }
}();
my_module.firstMethod();
Dom and Event
Dom

 Dom (document object modeling)
 Retrieving Nodes
   document.getElementById(id)


   document.getElementsByName(name)


   node.getElementsByTagName(tagNam
   e)
Document Tree Structure

     #document               <html>
                              <body>
         HTML                   <h1>Heading 1</h1>
                                     <p>Paragraph.</p>
                 HEAD
                                  <h2>Heading 2</h2>
                                     <p>Paragraph.</p>
                 BODY         </body>
                             </html>
                        H1
                             #text

                        P
                             #text

                        H2
                             #text

                        P
                             #text
firstChild        firstChild




                     H1


#text
        lastChild

                                               BODY
        firstChild
                                   lastChild




                     P


#text
        lastChild




        firstChild
                     H2


#text

        lastChild
                                                      child, sibling, parent




        firstChild
                     P


#text




        lastChild
child, sibling, parent


       BODY
                                 lastChild
firstChild




                          nextSibling                          nextSibling                         nextSibling
             H1                                    P                                  H2                                   P
                  previousSibling                      previousSibling                     previousSibling
firstChild




                                     firstChild




                                                                         firstChild




                                                                                                             firstChild
                     lastChild




                                                          lastChild




                                                                                              lastChild




                                                                                                                                  lastChild
             #text                                #text                               #text                               #text
child, sibling, parent


       BODY
                                       lastChild
              parentNode
firstChild




                                nextSibling                                nextSibling                               nextSibling
             H1                                           P                                       H2                                          P
                           previousSibling                            previousSibling                           previousSibling
              parentNode




                                                         parentNode




                                                                                                   parentNode




                                                                                                                                             parentNode
firstChild




                                           firstChild




                                                                                     firstChild




                                                                                                                               firstChild
                           lastChild




                                                                      lastChild




                                                                                                                lastChild




                                                                                                                                                          lastChild
             #text                                      #text                                     #text                                     #text
child, sibling, parent


       BODY
firstChild




                     nextSibling                    nextSibling                    nextSibling
             H1                              P                             H2                              P
firstChild




                               firstChild




                                                              firstChild




                                                                                             firstChild
             #text                          #text                          #text                          #text
childNodes



  BODY
      childNodes


  0                1       2        3



      H1               P       H2       P
Style

     node.style.stylename
          CSS                JavaScript
   background-          backgroundColor
    color
                         borderRadius
   border-radius
                         fontSize
   font-size
                         listStyleType
   list-style-type
   word-spacing         wordSpacing
   z-index              zIndex
Making Elements

document.createElement(tagName)

document.createTextNode(text)

node.cloneNode()
   Clone an individual element.

node.cloneNode(true)
   Clone an element and all of its descendents.


 The new nodes are not connected to the document.
Linking Elements

node.appendChild(new)

node.insertBefore(new, sibling)

node.replaceChild(new, old)

old.parentNode.replaceChild(new, old)
Removing Elements

node.removeChild(old)
  It returns the node.
  Be sure to remove any event handlers.


old.parentNode.removeChild(old)
innerHTML
                                             Parse

 The W3C standard does not provide access to the
  HTML parser.

 All A browsers implement Microsoft's innerHTML
  property.

 node.innerHTML = “<p> this is text
  </p>”;
Which Way Is Better?

 It is better to build or clone elements and append
  them to the document?

 Or is it better to compile an HTML text and use
  innerHTML to realize it?

 Favor clean code and easy maintenance.

 Favor performance only in extreme cases.
Events
                                                 Event

 The browser has an event-driven, single-
  threaded, asynchronous programming model.

 Events are targeted to particular nodes.


 Events cause the invocation of event handler
  functions.
Mouse Events

 The target is the topmost (z-index) node containing
  the cursor.
    click
    dblclick
    mousedown
    mousemove
    mouseout
    mouseover
    mouseup
Input Events

 The target is the node having focus.
    blur
    change
    focus
    keydown
    keypress
    keyup
    reset
    submit
Event Handlers

 Classic
   node["on" + type] = handler;

 Microsoft
   node.attachEvent("on" +
    type, handler);

 W3C
   node.addEventListener(type, handler, fal
    se);
Event Handlers

 The handler takes an optional event parameter.
      Microsoft does not send an event parameter, use the
      global event object instead.
Event Handlers

var handler = function (e) {
    e = e || event;
    var target =
        e.target || e.srcElement;
    ...
}
Bubbling


 Bubbling means that the event is given to the
  target, and then its parent, and then its
  parent, and so on until the event is canceled.
Why Bubble?

 Suppose you have 100 draggable objects.

 You could attach 100 sets of event handlers to
  those objects.

 Or you could attach one set of event handlers to
  the container of the 100 objects.
Cancel Bubbling

 Cancel bubbling to keep the parent nodes from
  seeing the event.

     e.cancelBubble = true;
     if (e.stopPropagation) {
         e.stopPropagation();
     }
Prevent Default Action

 An event handler can prevent a browser action associated
  with the event (such as submitting a form).

     e.returnValue = false;
     if (e.preventDefault) {
         e.preventDefault();
     }
     return false;
Introduction to YoolkUi
What is YoolkUi

 The YoolkUI is a comprehensive suite of
  controls, written with JavaScript and CSS, for
  building rich responsive windows style web
  applications
 It is an open source
 Copatible with
Componetns

 Events
   Dom event handler
   Object event hander following observer parttern
 Util: provides all necessary utilities methods
 Widget
   Container widget
   Control widget
 Ajax, Sadly we don’t provide any ajax helper
Dom event handler

  Help to bind the event and its handlers to
    dom
Var div = YK.domBuilder.create({tag: “div”, append:
document.body});
YK.Event.addDomListener(div, “click”, function(e){
      alert(“hello world”);
      YK.Event.stopBubble(e);
});
Object event handler

 Follow Observer parttern

Var obj = new Object();
YK.Event.addListener(obj, “showMe”, function(){
      alert(“show me please”);
});
YK.Event.trigger(obj, “showMe”);
YK.Util

 Provide all the utilities needed for Yoolkui.
 See http://ui.yoolk.com/yoolkui-
  documentation/
Container Widget

  Provide wrapper for control widget and
   position it accordingly.
  Complet list of Container widget
• YK.Accordion             •   YK.Scroller
• YK.Container             •   YK.Table
• YK.Dragger
• YK.Frame
• YK.Hbox
• YK.Vbox
• YK.LiquidBox
• YK.MultiPanelContainer
• YK.NoteBook
• YK.VPaned
• YK.HPanded
Control widget

      Have ui presentation
      Most of the time, will be wrapped around and
       positioned inside Container widget
      Complet list of control widget
•   YK.Button        •YK.EntryDropDown     •   YK.SmartEntry
•   YK.CheckButton   • YK.Image            •   YK.SmartEntryDropDon
•   YK.ClipBoard     • YK.JustifiedLabel   •   YK.TextEditor
•   YK.ComboBox      • YK.Label            •   YK.TextView
•   YK.ComboEntry    • YK.LiquidLabel      •   YK.UnicodeEditor
•   YK.DatePicker    • YK.List             •   YK.TreeView
•   YK.Dom           • YK.ListView
•   YK.Entry         • YK.RadioButton
•   YK.EntrySearch
Reference

 The theory of dom by Douglas Crockford
 A Quick Intro to Javascript by Rajat Pandit
  (rajat_pandit@ipcmedia.com)
 YoolkUi http://ui.yoolk.com

More Related Content

PPT
Advanced Javascript
PPT
Advanced JavaScript
PPT
Beginning Object-Oriented JavaScript
PPT
Advanced JavaScript
PPTX
Understanding Object Oriented Javascript - Coffee@DBG June
PDF
Prototype
PPT
Object Oriented JavaScript
PPTX
Javascript Prototype Visualized
Advanced Javascript
Advanced JavaScript
Beginning Object-Oriented JavaScript
Advanced JavaScript
Understanding Object Oriented Javascript - Coffee@DBG June
Prototype
Object Oriented JavaScript
Javascript Prototype Visualized

What's hot (20)

PPTX
Advanced JavaScript
PDF
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
PPT
Class and Objects in PHP
PDF
The many facets of code reuse in JavaScript
PDF
Object Oriented Programming with PHP 5 - More OOP
PPT
Oops in PHP By Nyros Developer
PDF
Clean coding-practices
PPTX
Oop in-php
PPT
Class 7 - PHP Object Oriented Programming
PPT
Php Oop
PPT
Oops in PHP
PDF
Clean code
PPTX
Object oreinted php | OOPs
PDF
Fundamental JavaScript [UTC, March 2014]
PDF
SOLID Deconstruction
PPTX
The Sincerest Form of Flattery
PPT
Introduction to OOP with PHP
PPTX
Object Oriented Programming In JavaScript
PDF
[A 3]Javascript oop for xpages developers - public
Advanced JavaScript
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Class and Objects in PHP
The many facets of code reuse in JavaScript
Object Oriented Programming with PHP 5 - More OOP
Oops in PHP By Nyros Developer
Clean coding-practices
Oop in-php
Class 7 - PHP Object Oriented Programming
Php Oop
Oops in PHP
Clean code
Object oreinted php | OOPs
Fundamental JavaScript [UTC, March 2014]
SOLID Deconstruction
The Sincerest Form of Flattery
Introduction to OOP with PHP
Object Oriented Programming In JavaScript
[A 3]Javascript oop for xpages developers - public
Ad

Viewers also liked (20)

PPTX
Reporting of anco
PPTX
Fotografía Documental
PDF
Tim Bartlett - Document Control Analyst
DOCX
Security is evolution
ODP
Razones para usar software libre
PPT
The OBREAU Tipod: A Tool for Finding Gold among the Rubble
PDF
Save Farmers!!!!
PPTX
Dreaming your story: Opportunities for Strengths Development
PPT
Ojo de fotografo
PDF
אבטחת ציוד קצה נייד
PPT
2. las fuentes de energia
DOCX
שירותי אבטחה בענן
PPTX
Demoweek
PPTX
Eyes on Extension: A model for diverse advisory leadership
PPT
Sesion 1 psicologia del consumidor
PPTX
Scada Security
PPTX
Convergencia Multimedia
PPTX
Todo se trata de infografías
PPT
3r eso tema 3 NATURALESA i SOCIETAT
PDF
La création de l’univers. french. français
Reporting of anco
Fotografía Documental
Tim Bartlett - Document Control Analyst
Security is evolution
Razones para usar software libre
The OBREAU Tipod: A Tool for Finding Gold among the Rubble
Save Farmers!!!!
Dreaming your story: Opportunities for Strengths Development
Ojo de fotografo
אבטחת ציוד קצה נייד
2. las fuentes de energia
שירותי אבטחה בענן
Demoweek
Eyes on Extension: A model for diverse advisory leadership
Sesion 1 psicologia del consumidor
Scada Security
Convergencia Multimedia
Todo se trata de infografías
3r eso tema 3 NATURALESA i SOCIETAT
La création de l’univers. french. français
Ad

Similar to Introduction to javascript and yoolkui (20)

PDF
JavaScript Core
KEY
Javascript tid-bits
PPTX
Ajaxworld
PPTX
Awesomeness of JavaScript…almost
PPT
Basic Javascript
PDF
JavaScript Primer
PDF
Scalable JavaScript
PPT
Javascript Object Oriented Programming
PPT
Java Script Patterns
PDF
Javascript basic course
PDF
Javascript
PPT
eXo SEA - JavaScript Introduction Training
PPTX
JavaScript OOPS Implimentation
KEY
JavaScript Neednt Hurt - JavaBin talk
KEY
PPTX
Object Oriented Javascript part2
PPTX
Object oriented javascript
PDF
Javascript for Intermediates
PPT
lecture 6 javascript event and event handling.ppt
JavaScript Core
Javascript tid-bits
Ajaxworld
Awesomeness of JavaScript…almost
Basic Javascript
JavaScript Primer
Scalable JavaScript
Javascript Object Oriented Programming
Java Script Patterns
Javascript basic course
Javascript
eXo SEA - JavaScript Introduction Training
JavaScript OOPS Implimentation
JavaScript Neednt Hurt - JavaBin talk
Object Oriented Javascript part2
Object oriented javascript
Javascript for Intermediates
lecture 6 javascript event and event handling.ppt

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Modernizing your data center with Dell and AMD
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
PDF
Approach and Philosophy of On baking technology
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Machine learning based COVID-19 study performance prediction
PDF
Empathic Computing: Creating Shared Understanding
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Cloud computing and distributed systems.
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Digital-Transformation-Roadmap-for-Companies.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Monthly Chronicles - July 2025
Modernizing your data center with Dell and AMD
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
NewMind AI Weekly Chronicles - August'25 Week I
Machine learning based COVID-19 study performance prediction
Empathic Computing: Creating Shared Understanding
Spectral efficient network and resource selection model in 5G networks
Cloud computing and distributed systems.
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Understanding_Digital_Forensics_Presentation.pptx

Introduction to javascript and yoolkui

  • 2. About Me  var name = “Suylong Khou”;  var profession = “Javascript Developer”;  var partTime = “Missionary”;  var myCore = “Give, and it will be given to you. A good measure, pressed down, shaken together and running over, will be poured into your lap. For with the measure you use, it will be measured to you.“.luke(6, 38);
  • 3. Data Types  Object  Function  Numbers  Strings  Booleans  null - a value that isn’t anything  undefined - default value for variables and parameters, value of missing members in the object etc
  • 4. Objects  Objects can contain data and methods  Objects can inherit from other objects  An object contain an unordered collection of name/value pairs  Values can be any type including other objects  JSON
  • 5. Object Literals  Objects are wrapped in {}  Names can be string  Value can be an expression  ; used for separation  , separate pairs
  • 6. Object Example var myobject = { name : “Jack Appleseed”, “data”: { foo: 10, bar: 20} }; var data = myobject.data; var foo = myobject.data.foo;
  • 7. typeof Prefix Operator  The typeof prefix operator returns a  string identifying the type of value  Use instanceof instead
  • 8. Array  Array inherits from Object (like every other object in JavaScript)  No need to provide length when creating a new one  Unlike object they have a length member and is always 1 larger than the highest subscript
  • 9. Array Methods  concat  join (can also be used for concatenating multiple strings)  pop  push  slice  sort  splice
  • 10. Checking for Array • Use construction value.constructor === Array • User instanceof value instanceof Array
  • 11. Function  They are first class Objects  Can be passed, stored and returned just like any value  Inherit from object  Function can appear anywhere an expression can appear
  • 12. Function Cont...  Functions can be contained inside other functions  Inner function has access to the variable and parameters of the function it is contained within  This is static or lexical scoping  The scope that inner function has access to continues even after the parent function has returned is called Closure
  • 13. Closure function sayHello2(name) { var text = 'Hello ' + name; // local variable var sayAlert = function() { alert(text); } return sayAlert; } var say2 = sayHello2(“Foo”); Say2();
  • 14. Function Cont...  Function inside an object is called a method  When invoked with too many arguments, the rest are ignored  When invoked with fewer arguments,  the rest are set to undefined
  • 15. Function’s arguments var showMe = function(f00, bar){ return foo + bar, } showMe(“foo”, “bar”, “foobar”); //Last argument will be ignore showMe(“foo”) //bar will be undefined
  • 16. Function Cont...  When a function is invoked in method format, this refers to the object containing it. var foo = { baz: 10, bar: function() { console.log(this.baz); } }; foo.bar();
  • 17. Function Cont...  When object is invoked in function, this refers to the global object var global_variable = 5; function test() { console.log(this.global_variable); } test();
  • 18. Function Cont...  When new Function is used (implicit return is optional), then this returns the new object created var Test = function(id) { this.something = id; this.foo = function() { console.log('this is a test: ' + this.something); } } var o = new Test(10), i = new Test(111); o.foo(); i.foo();
  • 19. Function (arguments)  When function is invoked, in addition to its parameters it has a special parameter called arguments  Contains all arguments from invocation  arguments.length will tell you how many arguments were passed  arguments is not of type Array even  though it has length
  • 20. Function (arguments) var foo = function() { var a = new Array(); console.log( typeof a ); console.log( typeof arguments ); console.log( arguments instanceof Object ); console.log( arguments instanceof Array ); } foo();
  • 21. (global) Object  As crockford says, the object that dare not speak of its name  It is the container for all global variables and all built in objects  On browsers window is the global object  Variables defined with a var makes it local to the scope
  • 22. GLOBAL VARIABLES ARE EVIL  Un-namespaced values can clash each others values  Use of it should be minimized or gotten rid of totally  Variables defined in the function / module should start with var otherwise they have a global scope
  • 24. Object-Oriented Basics  Object (instance): representation of a "thing" (someone or something)  Class - a blueprint, or recipe for an object  Encapsulation : illustrates the fact that an object contains (encapsulates) :  Data (stored in properties)  The means to do something with the data (using methods)  Inheritance
  • 25. Object Creation  Two simple ways var obj = new Object(); obj.name = “Foo”; obj.say = function(){ return “hello”;}; var obj = { name: “Foo”, say: function(){ return “helllo”; } }
  • 26. Methods  When a property is a function we can call it a method var object = { method: function(){ alert("here’s method"); } }
  • 27. prototype  JavaScript functions work as methods, constructors and modules  It has Prototypal Inheritance, which offers great expressive powers  All objects are directly or indirectly linked to Object.prototype
  • 28. prototype  Each object is linked to its parent via a magic link  When a member is accessed the compiler looks at the object and then looks up to its parent via the magic link  It keeps going all the way up to Object.prototype  Go to console of firebug and type Object.prototype
  • 29. prototype  Looking for my_object.foo, found it in the object itself  Looking for my_object.baz looks in the object and if it doesn’t find it there it goes to my_object_parent which is my_object.prototype  Looking for my_object.some_random_member can’t find it in the object, look at my_object_parent, can’t find it  there either, goes to Object can’t find it there and is set to undefined
  • 30. prototype var Person = function(){ this.name = “Mr.Foo”; this.callMe = function(){ alert(“I am “ + this.name ); } } var personObj = new Person(); personObj.callMe(); personObj.constructor(); personObj.myFoo(); //will return undefined
  • 31. Object Augmentation  New members can be added to any object Person.prototype.callMeAgain = function(){ alert(“I said my name is: “ + this.name); }; personObj.callMeAgain();
  • 32. Prototype usage  callMeAgain() is a property of the prototype object  but it behaves as if it's a property of the dude object
  • 33. Own properties vs. prototype’s personObj.hasOwnProperty(“callMe”);  will return true personObj.hasOwnProperty(“callMeAgain”);  will return false;
  • 35. Inheritance  OOP ensures code reuse  Two forms of OOP  Classical with Mixin  Prototypal
  • 36. Prototypal Inheritance var Boy = function(){}; Boy.prototype = new Person(); var boyObj = new Boy(); boyObj.callMe();
  • 37. Inheritance through Mixin var Person = function(name){ this.greet = function(){ alert("Hello, I'm " + name); } }; var Employee = function(name){ Person.apply(this, [name]); this.getTeam = function(){ return "UI Library";} } //instantiate object of Employee var employee = new Employee("Borey"); employee.greet(); var team = employee.getTeam(); alert("Team: " + team);
  • 38. Singleton  There is no need to produce a class-like constructor for an object that will have exactly one instance  This is typical of JavaScript applications  Use an object literal to get started instead
  • 39. Module Pattern  The methods of a singleton can enjoy access to shared private datum and private methods  Variables defined in a module are only visible in a module  Variables defined in a function are only visible to the function  Function can be used as module containers
  • 40. Module Pattern var my_module = function() { var privateVariable, privateFunction = function() { // stuff }; return { firstMethod: function(a,b) { // can access privateVariable // can access privateFunction } } }(); my_module.firstMethod();
  • 42. Dom  Dom (document object modeling)  Retrieving Nodes  document.getElementById(id)  document.getElementsByName(name)  node.getElementsByTagName(tagNam e)
  • 43. Document Tree Structure #document <html> <body> HTML <h1>Heading 1</h1> <p>Paragraph.</p> HEAD <h2>Heading 2</h2> <p>Paragraph.</p> BODY </body> </html> H1 #text P #text H2 #text P #text
  • 44. firstChild firstChild H1 #text lastChild BODY firstChild lastChild P #text lastChild firstChild H2 #text lastChild child, sibling, parent firstChild P #text lastChild
  • 45. child, sibling, parent BODY lastChild firstChild nextSibling nextSibling nextSibling H1 P H2 P previousSibling previousSibling previousSibling firstChild firstChild firstChild firstChild lastChild lastChild lastChild lastChild #text #text #text #text
  • 46. child, sibling, parent BODY lastChild parentNode firstChild nextSibling nextSibling nextSibling H1 P H2 P previousSibling previousSibling previousSibling parentNode parentNode parentNode parentNode firstChild firstChild firstChild firstChild lastChild lastChild lastChild lastChild #text #text #text #text
  • 47. child, sibling, parent BODY firstChild nextSibling nextSibling nextSibling H1 P H2 P firstChild firstChild firstChild firstChild #text #text #text #text
  • 48. childNodes BODY childNodes 0 1 2 3 H1 P H2 P
  • 49. Style  node.style.stylename CSS JavaScript  background-  backgroundColor color  borderRadius  border-radius  fontSize  font-size  listStyleType  list-style-type  word-spacing  wordSpacing  z-index  zIndex
  • 50. Making Elements document.createElement(tagName) document.createTextNode(text) node.cloneNode()  Clone an individual element. node.cloneNode(true)  Clone an element and all of its descendents.  The new nodes are not connected to the document.
  • 52. Removing Elements node.removeChild(old)  It returns the node.  Be sure to remove any event handlers. old.parentNode.removeChild(old)
  • 53. innerHTML Parse  The W3C standard does not provide access to the HTML parser.  All A browsers implement Microsoft's innerHTML property.  node.innerHTML = “<p> this is text </p>”;
  • 54. Which Way Is Better?  It is better to build or clone elements and append them to the document?  Or is it better to compile an HTML text and use innerHTML to realize it?  Favor clean code and easy maintenance.  Favor performance only in extreme cases.
  • 55. Events Event  The browser has an event-driven, single- threaded, asynchronous programming model.  Events are targeted to particular nodes.  Events cause the invocation of event handler functions.
  • 56. Mouse Events  The target is the topmost (z-index) node containing the cursor.  click  dblclick  mousedown  mousemove  mouseout  mouseover  mouseup
  • 57. Input Events  The target is the node having focus.  blur  change  focus  keydown  keypress  keyup  reset  submit
  • 58. Event Handlers  Classic  node["on" + type] = handler;  Microsoft  node.attachEvent("on" + type, handler);  W3C  node.addEventListener(type, handler, fal se);
  • 59. Event Handlers  The handler takes an optional event parameter.  Microsoft does not send an event parameter, use the global event object instead.
  • 60. Event Handlers var handler = function (e) { e = e || event; var target = e.target || e.srcElement; ... }
  • 61. Bubbling  Bubbling means that the event is given to the target, and then its parent, and then its parent, and so on until the event is canceled.
  • 62. Why Bubble?  Suppose you have 100 draggable objects.  You could attach 100 sets of event handlers to those objects.  Or you could attach one set of event handlers to the container of the 100 objects.
  • 63. Cancel Bubbling  Cancel bubbling to keep the parent nodes from seeing the event. e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); }
  • 64. Prevent Default Action  An event handler can prevent a browser action associated with the event (such as submitting a form). e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } return false;
  • 66. What is YoolkUi  The YoolkUI is a comprehensive suite of controls, written with JavaScript and CSS, for building rich responsive windows style web applications  It is an open source  Copatible with
  • 67. Componetns  Events  Dom event handler  Object event hander following observer parttern  Util: provides all necessary utilities methods  Widget  Container widget  Control widget  Ajax, Sadly we don’t provide any ajax helper
  • 68. Dom event handler  Help to bind the event and its handlers to dom Var div = YK.domBuilder.create({tag: “div”, append: document.body}); YK.Event.addDomListener(div, “click”, function(e){ alert(“hello world”); YK.Event.stopBubble(e); });
  • 69. Object event handler  Follow Observer parttern Var obj = new Object(); YK.Event.addListener(obj, “showMe”, function(){ alert(“show me please”); }); YK.Event.trigger(obj, “showMe”);
  • 70. YK.Util  Provide all the utilities needed for Yoolkui.  See http://ui.yoolk.com/yoolkui- documentation/
  • 71. Container Widget  Provide wrapper for control widget and position it accordingly.  Complet list of Container widget • YK.Accordion • YK.Scroller • YK.Container • YK.Table • YK.Dragger • YK.Frame • YK.Hbox • YK.Vbox • YK.LiquidBox • YK.MultiPanelContainer • YK.NoteBook • YK.VPaned • YK.HPanded
  • 72. Control widget  Have ui presentation  Most of the time, will be wrapped around and positioned inside Container widget  Complet list of control widget • YK.Button •YK.EntryDropDown • YK.SmartEntry • YK.CheckButton • YK.Image • YK.SmartEntryDropDon • YK.ClipBoard • YK.JustifiedLabel • YK.TextEditor • YK.ComboBox • YK.Label • YK.TextView • YK.ComboEntry • YK.LiquidLabel • YK.UnicodeEditor • YK.DatePicker • YK.List • YK.TreeView • YK.Dom • YK.ListView • YK.Entry • YK.RadioButton • YK.EntrySearch
  • 73. Reference  The theory of dom by Douglas Crockford  A Quick Intro to Javascript by Rajat Pandit (rajat_pandit@ipcmedia.com)  YoolkUi http://ui.yoolk.com