Weitere ähnliche Inhalte Ähnlich wie JavaScript Coding with Class (20) Kürzlich hochgeladen (20) JavaScript Coding with Class2. Who is David Walsh?
Software Engineer for SitePen
MooTools Team Member - Add real photo of me
David Walsh Blog scribe - Slide in caricature
Script & Style founder
10 years working experience
@davidwalshblog
© SitePen, Inc. All Rights Reserved
3. Class?
Class patterns
As featured in most programming languages
Object-oriented methodology employed
Beautiful code
.... a.k.a. programmer porn
Adheres to basic JavaScript coding practices
© SitePen, Inc. All Rights Reserved
7. (not class)
Add photo of:
- Jordon
- Boy George
© SitePen, Inc. All Rights Reserved
9. Classes in JavaScript
True “classes” are not provided by JavaScript
....even though class is a reserved word
Enclosure patterns, functions, and their prototypes are used
to simulate classes
Toolkits like Dojo and MooTools abstract those patterns to
allow developers to create powerful, flexible classes
© SitePen, Inc. All Rights Reserved
10. Why Classes?
Easier to read, understand, & maintain
Unified API despite type of task
Inheritance Patterns
Easy to extend
“Don’t Repeat Yourself” philosophy employed
Portable & Modular
Take only what you need!
Used in most other languages
Tried and tested; stick to what we’re used to
© SitePen, Inc. All Rights Reserved
11. Key Class Components
Constructor
Fires upon instance creation
Properties or “Options”
Configures an instance’s behavior
Methods
Accomplish tasks within the instance
© SitePen, Inc. All Rights Reserved
12. Key Class Concepts
Extending
Builds upon existing classes for more goal-specific behavior
Uses the existing class’ prototype as its base
DON’T REPEAT YOURSELF
Implementing and “monkey patching”
Add or modify behavior on existing objects via prototype mod.
May keep reference to original method and call anywhere within
the replacing method
Lots of methods and options
Makes extending much, much easier!
© SitePen, Inc. All Rights Reserved
13. Dojo & MooTools Class Similarities
Both use prototypal inheritance
Objects are provided another object as its prototype
jQuery, in contrast, is a “functional” lib
Both provide an easy interface for creating complex classes
Both provide methods for calling a parent class’ method of
the same name
Both are extremely modular
© SitePen, Inc. All Rights Reserved
14. JavaScript Prototypal Inheritance
// Crockford’s latest implementation
// If Object.create isn’t supported by the browser...
if (typeof Object.create !== 'function') {
// Implement it!
Object.create = function (proto) {
function F() {}
F.prototype = proto;
return new F();
};
}
var newObject = Object.create(oldObject);
// Use the new class
var myInstance = new newObject({ /* props */ });
// Available: http://javascript.crockford.com/prototypal.html
© SitePen, Inc. All Rights Reserved
15. MooTools’ Class
Class is a standard MooTools module; creates a new “class”
Accepts one argument: an object with key/value methods and
properties
Detects predetermined, “special” property names to manage
class creation and dependencies
Returns the newly created class
Adds additional methods to each class
toElement
implement
© SitePen, Inc. All Rights Reserved
16. MooTools’ Class: Special Properties
Extends
The existing class which the new class should extend
Implements
An array of existing classes to be mixed in
initialize
The class constructor
Varies in signature depending on required arguments to create an
instance of the class
Last argument is usually an options object with instance-specific
properties
© SitePen, Inc. All Rights Reserved
17. MooTools Class Structure
// Declare the new Class
var MyClassName = new Class({
// Extends an existing class; use as base prototype
Extends: SomeExistingClass,
// Mix in properties from these classes/objects as well
Implements: [Options, Events],
// Default options list
options: {
myOpt: true
},
// Constructor
initialize: function(someElement, options) {
this.setOptions(options);
this.someElement = document.id(someElement); // Accepts IDs or Nodes
},
// Some class method
utilityMethod: function(arg1, arg2) {
this.parent(arg1, arg2);
this.fireEvent('complete');
}
});
© SitePen, Inc. All Rights Reserved
19. Inline Slideshow - No Class
window.addEvent('domready',function() {
// Settings
var showDuration = 3000;
var container = $('slideshow-container');
var images = container.getElements('img');
var currentIndex = 0;
var interval;
// Opacity and fade
images.each(function(img,i){
if(i > 0) {
img.set('opacity',0);
}
});
// The “Worker”
var show = function() {
images[currentIndex].fade('out');
images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 :
0].fade('in');
};
// Start once the page is finished loading
window.addEvent('load',function(){
interval = show.periodical(showDuration);
});
});
© SitePen, Inc. All Rights Reserved
20. Classy Slideshow
var SimpleSlideshow = new Class({
options: {
showDuration: 3000
},
Implements: [Options, Events],
currentIndex: 0,
initialize: function(container, elements, options) {
//settings
this.container = $(container);
this.elements = $$(elements);
this.setOptions(options);
// ....
}
show: function(to) { /* fade in/out logic */ },
start: function() { /* interval logic */ },
stop: function() { /* clear interval logic */ },
// more methods...
});
// Using the class....
var show = new SimpleSlideshow('slideshow', 'img', {
showDuration: 2000
});
show.start();
© SitePen, Inc. All Rights Reserved
21. Sample MooTools Class: Request.Twitter
// Declare the new Class
Request.Twitter = new Class({
// Extends an existing class; use as base prototype
Extends: Request.JSONP,
// Create a list of options
Implements: [Linkify],
// Provide the default options
options: {
url: "http://twitter.com/statuses/user_timeline/{term}.json",
data: { count: 5 }
},
// Constructor
initialize: function(term, options) {
this.parent(options); // pass options to “parent” class
this.options.url = this.options.url.substitute({ term: term });
},
// Success Event
success: function(data, script) {
data[0].each(function(tweet) {
tweet.text = this.linkify(tweet.text);
}, this);
this.parent(data, script);
}
});
© SitePen, Inc. All Rights Reserved
22. Sample MooTools Class: Request.Twitter (c...)
(function() {
// Create a new instance
var request = new Request.Twitter("davidwalshblog", {
// Customize an options:
data: { count: 20 }, // Load 20 tweets instead of the default 5
// When the request succeeds...
onComplete: function(tweets) {
console.warn("Tweet received: ", tweets);
}
});
// Send a request for tweets
request.send();
})();
© SitePen, Inc. All Rights Reserved
23. Sample MooTools Class: implement()
// Extend the existing class’ prototype with properties or methods
MyExistingClass.implement({
// Basic property
isMental: true,
// New method!
someNewMethod: function() {
// Do some new stuff in here
}
});
// A realistic usage
Request.Twitter.implement({
// Linkifies the a tweet!
linkify: function(text) {
return text.replace(/(https?://[w-:;?&=+.%#/]+)/gi, '<a href="$1">$1</a>')
.replace(/(^|W)@(w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
.replace(/(^|W)#(w+)/g, '$1#<a href="http://search.twitter.com/search?q=
%23$2">$2</a>');
}
});
© SitePen, Inc. All Rights Reserved
24. Classes with Dojo: dojo.declare
dojo.declare creates Dojo classes
Traditional class creation methods since Dojo 0.x
Dojo 1.6+ uses AMD format for
Accepts 3 arguments:
Class name with namespace
null, single class, or an array of inheritance, if any
First object in array is the extender
Subsequent objects act as mixins
Object with methods and properties with default values
Adds several additional properties and methods to each class
© SitePen, Inc. All Rights Reserved
25. Dojo’s dojo.declare: Special Properties
constructor
The class constructor
Varies in signature depending on required arguments to create an
instance of the class
Last argument is usually an options object with instance-specific
properties
Automatically fired up the inheritance chain
Dijit’s _Widget and _Templated provides additional
special methods for UI widgets
postMixInProperties, postCreate, startup
© SitePen, Inc. All Rights Reserved
26. Dojo Class Structure
// Provide the class
dojo.provide('mynamespace.ResourceName');
// Require the class dependencies
dojo.require('dojo.resource1');
dojo.require('dojo.resource2');
// Declare the new class with dojo.resources1 as the base prototype, 2 as a mixin
dojo.declare('mynamespace.ResourceName', [dojo.resource1, dojo.resource2], {
// Add a custom property
age: 10,
// Constructor to do something
constructor: function(args) {
this.dogAge = (args.age || this.age) * 7;
},
// Add a custom method
overridenMethod: function(arg1) {
// Call parent method
this.inherited(arguments);
}
});
© SitePen, Inc. All Rights Reserved
27. Dojo Class Structure: Usage
// Require the class
dojo.require('mynamespace.ResourceName');
// Create an instance and work with it!
var myInstance = new mynamespace.ResourceName({
age: 20
});
myInstance.doSomething();
myInstance.doSomethingElse();
© SitePen, Inc. All Rights Reserved
28. Sample Dojo Class: dojo.Stateful
dojo.provide("dojo.Stateful");
// Declare the class
dojo.declare("dojo.Stateful", null, {
postscript: function(mixin){
if(mixin){
dojo.mixin(this, mixin);
}
},
get: function(/*String*/name){
return this[name];
},
set: function(/*String*/name, /*Object*/value){
if(typeof name === "object"){
for(var x in name){
this.set(x, name[x]);
}
return this;
}
var oldValue = this[name];
this[name] = value;
if(this._watchCallbacks){
this._watchCallbacks(name, oldValue, value);
}
return this;
},
© SitePen, Inc. All Rights Reserved
29. Sample Dojo Class: dojo.Stateful continued...
watch: function(/*String?*/name, /*Function*/callback){
var callbacks = this._watchCallbacks;
if(!callbacks){
var self = this;
callbacks = this._watchCallbacks = function(name, oldValue, value, ignoreCatchall){
var notify = function(propertyCallbacks){
for(var i = 0, l = propertyCallbacks && propertyCallbacks.length; i < l; i++){
try{
propertyCallbacks[i].call(self, name, oldValue, value);
}catch(e){
console.error(e);
}
}
};
notify(callbacks[name]);
if(!ignoreCatchall){
notify(callbacks["*"]); // the catch-all
}
}; // we use a function instead of an object so it will be ignored by JSON conversion
}
if(!callback && typeof name === "function"){
callback = name;
name = "*";
}
var propertyCallbacks = callbacks[name];
if(typeof propertyCallbacks !== "object"){
propertyCallbacks = callbacks[name] = [];
}
propertyCallbacks.push(callback);
return {
unwatch: function(){
propertyCallbacks.splice(dojo.indexOf(propertyCallbacks, callback), 1);
}
};
}
© SitePen, Inc. All Rights Reserved
30. dojo.extend
// Require the resource
dojo.require("dojo.Deferred");
// Add new properties and functions to the dojo.Deferred prototype
dojo.extend(dojo.Deferred, {
addCallback: function (/*Function*/callback) {
return this.addCallbacks(dojo.hitch.apply(dojo, arguments));
},
addErrback: function (/*Function*/errback) {
return this.addCallbacks(null, dojo.hitch.apply(dojo, arguments));
},
addBoth: function (/*Function*/callback) {
var enclosed = dojo.hitch.apply(dojo, arguments);
return this.addCallbacks(enclosed, enclosed);
},
fired: -1
});
© SitePen, Inc. All Rights Reserved
31. Sample Dojo Class: AMD
define([
"dojo/_base/declare",
"./ValidationTextBox",
"./ComboBoxMixin"
], function(declare, ValidationTextBox, ComboBoxMixin){
return declare("dojo/_base/declare", [ValidationTextBox, ComboBoxMixin], {
// Add more properties and methods here
}
});
© SitePen, Inc. All Rights Reserved
32. Dojo & MooTools Class Differences
Dojo provides a custom loader
Retrieve resources (classes, templates, resources, ...) dynamically
Uses synchronous XHR requests
Easier for “change and refresh” development
Cross-domain loading even works great!
MooTools provides no loader, but a builder is available
Namespacing
Dojo is built to work with namespaces
MooTools-provided classes are global, and are not placed in
namespaces unless specified otherwise
© SitePen, Inc. All Rights Reserved
33. Tips for Creating Classes
Make your utility classes flexible
Easier to use from project to project
Use meaningful property and method names
Allows for ease in development, both inside the class and out
Stick with the toolkit’s coding style
Spacinging, naming, structure, namespacing
Use lots of methods
Allows for easier extension and customization
© SitePen, Inc. All Rights Reserved
34. Finding and Sharing Classes
MooTools Forge
Massive repository of MooTools classes
Class types include Fx, Interface, Media, Request, Utilities, and
more!
Several available on David Walsh Blog
DojoX
Dojo’s official “plugin” division
Features many enterprise-quality sub-libraries, like GFX, Charting
Features “enhancers” for existing Dojo and Dijit classes
No official public, user-driven plugin repository...yet
© SitePen, Inc. All Rights Reserved
35. Stay Classy!
There’s more to JavaScript than j(ust)querying for DOM
nodes, creating animations, and making simple AJAX requests
JavaScript class structures allow for ALL types of task
management, not just DOM node-related tasks
Consistent, coherent class APIs allow for faster, flexible
development regardless of task
© SitePen, Inc. All Rights Reserved
Hinweis der Redaktion \n \n \n \n \n \n &#x201C;There are three boobs on this slide; should have put one over Piers&#x2019; face&#x201D;\n\n&#x201C;Oh hey, I missed a boob on this slide&#x201D;\n \n \n Say that there are exceptions to every rule, and it&#x2019;s up to the developers to make each of the above true.\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n