essential yui
DESCRIPTION
Brief introduction to Yahoo's YUI library. Given as a presentation to college students who were new to JavaScript.Discusses DOM manipulation,TRANSCRIPT
Why do we need libraries?
• The DOM is difficult to use, verbose, and inconsistent (see DOM levels). • We must always respect the
global namespace !• Building advanced web
applications requires abstraction. • Leveraging other developer’s
code makes our lives easier.
The YUI Seed
<html><body>
<!-- your page content --><!-- YUI seed--> <script src=“…"></script><script src=“…">
// your JavaScript</script>
</body></html>
Quiz// finds the greatest common divisor function gcd(a, b) {
if(b === 0) return a;
else { x = a % b; return gcd(b, x);
} } x = 5; y = gcd(12, 4) + x; // what is y?
DOM nodes
var d = document;
var body = d.getElementsByTagName(‘body’)[0],p = d.createElement(‘p’),txt = d.createTextNode(‘Hello world!’);
body.appendChild(p.appendChild(txt));
DOM nodes
YUI().use(‘node’, function(Y) {
var body = Y.one(‘body’); body.append(Y.Node.create(
‘<p>Hello world!</p>’);
});
DOM Events
YUI().use(‘event’, function(Y) {
var button = Y.one(‘#button’);
Y.on(‘click’, function(e) { alert(‘hello’); });});
DOM EventsYUI().use(‘event’, function(Y) {
var mask = Y.one(‘#mask’);
Y.on(‘click’, function(e) {
e.preventDefault();mask.show();
}, ‘a#button’);});
AjaxYUI().use(‘io’, function(Y) { var handler = function(id, o, args) { Y.one(‘body’).append(o.responseText); });
Y.on(‘io:complete’, handler); Y.io(‘/users/profile?user_name=derrick’);});
var Animal = function(n) {var noise = n;this.makeNoise = function() {
alert(noise); }
};
var Dog = function () {this.bark = function() {
this.makeNoise(); }
};
Dog.prototype = new Animal(‘woof!’);
var Mammal = function() {this.baby = function() {
return new Mammal();}
};
Mammal.prototype = new Animal(); // uh oh…Dog.prototype = new Mammal(‘woof!’); fido = new Dog();fido.bark(); // undefined
fido instanceof Dog //truefido instanceof Mammal // truefido instanceof Animal //true
The Prototype Chain
Dog (fido)
bark__proto__
Animal
noisemakeNoise__proto__
Mammal
baby__proto__
{ }
What happened when fido.bark() ?
We were unable to provide the instance of Animal the correct argument when instanciated. The noise private field was never set.
YUI OO Utilities
• Native JavaScript OO• Y.extend (pseudo-classical)• Y.Object (prototypal)
• Synthetic OO • Y.augment (multiple
inheritance)• Y.Plugin (expressive, flexible)• Y.Base (feature rich out-of-the-
box)
var Animal = function(n) {var noise = n;this.makeNoise = function() {
alert(noise); }
};var Dog = function () {
Dog.superclass.constructor.apply(this, arguments);
this.bark = function() { this.makeNoise();
}};
Y.extend(Dog, Animal);
YUI().use(‘datatable’, …);
YUI().use(‘panel’, …);
You may retrieve any modules available on the Yahoo! CDN using the YUI loader.