SlideShare a Scribd company logo
What’s up with Prototype and
script.aculo.us? (Shiny things in Spinoffsland)

Christophe Porteneuve
CTO, Ciblo.net + Prototype Core member
Did you guys catch our Prototype
Developer Day?

• That was on Monday morning
 • Bringing the community together
 • Discussing contributions (to code, to docs)
 • Several Prototype Core members
 • Large Q&A session
• Awesome stuff!
What we’re going to see

• Prototype 1.6 → 1.6.0.3
 • Custom events
 • Class system
 • Other various improvements
• Where Prototype’s headed
 • Prototype 1.6.1 then 2.0
 • Sprockets, PDoc
• Where script.aculo.us is headed (Scripty2)
Prototype 1.6
Prototype 1.6

• “Hey, that was almost a year ago!”
 • Yeah, but never discussed at TAE yet (plus, 1.6.0.3 now…)
 • And a lot of good stuff in there!
• Custom events and dom:loaded
• New class system, with inheritance
• New Function-related stuff
• Ajax.Response
• Countless other improvements and fixes
Custom events: overview

• Events our own JS code triggers
• Attached to DOM nodes
• Bubble like regular DOM events
• Publish/subscribe model: fire/observe
• Major benefits
 • Encapsulation (internal behaviors are not exposed)
 • Loose coupling (anyone can trigger/observe any event)
 • Ability to bubble favors event delegation
Custom events: naming and availability

• How do we tell a custom event from a native one?
 • The custom event’s name must have 1+ colon
 • e.g. dom:loaded, content:updated, effect:finished
• You don’t need to “register” the event
 • You just observe / fire it.
• Custom events available on…
 • Any DOM node
 • The document object
Custom events: “creating” them

• Just observe one somewhere in your code

initComputation: function() {
  var target = this.element.down('.computed'), that = this;

    function recompute() {
      target.update(that.getComputedValue());
    }
    document.observe('data:changed', recompute);
}
Custom events: triggering them

• Simply call fire on the relevant DOM element



new Field.Observer('edtReqTaxRate', 0.5, function(field, value) {
  field.fire('data:changed');
});
Custom events: the memo property

initComputation: function() {
  var target = this.element.down('.computed'), that = this;

    function recompute(e) {
      target.update(e && e.memo ? e.memo : that.options.value);
    }
    recompute();
    document.observe('data:changed', recompute);
}

new Field.Observer('edtReqTaxRate', 0.5, function(field, value) {
  field.fire('data:changed', value);
});
Custom events: already much in style

• Especially by UI-oriented third-party libraries
 • Lets them create a full communication scheme between
   their widgets with no coupling whatsoever
• Prototype UI
 • http://prototype-ui.com
• LivePipe UI (f.k.a. Control.Suite)
 • http://livepipe.net/
dom:loaded

• Our first “standard” custom event
• Triggers right after DOM load
• So just forget
 Event.observe(window, 'load', initPage);

• And use
 document.observe('dom:loaded', initPage);
A note about stopObserving

• You can make partial calls now
• Omit the handler
 myEditor.stopObserving('change');

 • All handlers for this event on this element
• Omit the event too
 myEditor.stopObserving();

 • All handlers on all events on this element
• Easier cleanup
More Event goodness

• Guaranteed even methods and properties
 • relatedTarget, pageX, pageY
 • stopPropagation(), preventDefault(), stopped
• Click detection
 • isLeftClick(), isMiddleClick(), isRightClick()
• Pointer position
 • pointer(), pointerX(), pointerY()
A note on event binding

• Pre-1.6, handlers were “unbound” by default
 • Unless you had bound them explicitly, they’d end up using
   the window scope
• Starting with 1.6, handlers are bound to the
 subject of your observe call by default
 • If you bound them explicitly, as always, that prior binding
   will be retained.
New class system

• The idea: ease up traditional OOP constructs and
 behaviors
 • Inheritance
 • Mix-ins
 • Method overriding with access to inherited version
• Backward-compatible API
Ye Olde Class

var MyClass = Class.create({
  initialize: function(…) {
                                  • Key issues:
     // “Constructor” code here    • initialize required,
  },
                                     even if empty
  publicMethod1: function(…) {
  },
                                   • Can’t give a parent
                                     class
  …
});                                • Can’t override
                                     methods easily
The new class syntax

var MyClass = Class.create([parentClass, ][mixIns…, ]{
   [initialize: function(…) { … },]
   publicMethod1: …,
   …
})

• We can provide a single parent class
 • We then handle the prototype chaining for it
• We can provide 1+ “mixins” (modules)
 • Bunches of methods that get blended in the prototype.
• initialize is optional (an empty one will fill in)
Inheritance becomes a breeze

var XMLParser = Class.create({
  initialize: function(source) { … },
  …
});

var XHTMLParser = Class.create(XMLParser, {
  …
});

var AtomParser = Class.create(XMLParser, {
  …
});
Free stuff you get

• Every instance has a constructor
• Every class has a superclass and subclasses
XMLParser.superclass          //   =>   null
XHTMLParser.superclass        //   =>   XMLParser
AtomParser.superclass         //   =>   XMLParser
XMLParser.subclasses          //   =>   [XHTMLParser, AtomParser]

var parser = new XHTMLParser(someXHTMLSource);

parser.constructor            // => XHTMLParser
parser.constructor.superclass // => XMLParser
Mixing in modules

• A module is just a bag of properties/methods
• You can mix as many of those as you want at class
 creation time.
var FeedAnalyzer = {
   // methods…
};
…
var AtomParser = Class.create(XMLParser, FeedAnalyzer,
   MarkupFixer, StandardNamespaceHandler, {
   …
});
Class methods

• These are just methods on the Class object itself,
 so we can resort to good ol’ Object.extend.
var MyGenericClassMethods = {
   // methods…
};
…
Object.extend(AtomParser, MyGenericClassMethods);
Object.extend(AtomParser, {
   adHocMethod1: …,
   adHocMethod2: …,
   …
});
Adding methods post-declaration

• Every class has a addMethods method that mixes
 anything module-like in.
• It’s actually used on your modules (and custom
 methods) at creation time.
var UberCoolMethodsIGotJustNow = {
   leverageMicroFormats: …,
   turnIntoiPhoneUIs: …,
   turnIntoUniversalWidgets: …
};

AtomParser.addMethods(UberCoolMethodsIGotJustNow);
Accessing overridden methods

• Insert a $super first argument. That’s it.
var XMLParser = Class.create({
  initialize: function(source) { … },
  …
});

var AtomParser = Class.create({
  initialize: function($super, source, options) {
     $super(source);
     // Handle options
  },
  …
});
Function-fu

• Prototype 1.6 introduced a lot of new methods on
 function so you can reduce custom anonymous
 wrappers and go wild (but reasonable) with AOP
 • curry, rescuer of useless binds
 • delay and defer, because patience is a virtue
 • wrap, because AOP / Decorator can rock
 • argumentNames (aka Hackish The First)
Spicying up your code with curry

• You know how you always use bind(null,…) just
 because you need partial application?
 $('preview').observe('mousewheel:up', shiftZoom.bind(null, 125));
 $('preview').observe('mousewheel:down', shiftZoom.bind(null, 80));


• Don’t do it.
• That’s what curry is for:
 $('preview').observe('mousewheel:up', shiftZoom.curry(125));
 $('preview').observe('mousewheel:down', shiftZoom.curry(80));
curry vs. bind

• You should use bind when…
 • You actually need to bind (set the semantics of this)
 • It doesn’t matter whether you want to pre-fill arguments!
• You should use curry when…
 • You need to pre-fill arguments
 • And you don’t care about the binding, or more specifically
  don’t want to change it.
Deferring execution: delay and defer

• Schedule execution of a snippet of JS for later
 • Either a specific time later
 • Or ASAP—typically right after the DOM got a moment to
   breathe in your recent updates
• function.delay(seconds)
• defer is the “ASAP” case, and is just…
 • delay.curry(0.1) :-)
 • Essentially works because of single-threadedness
Classical defer use-case

• You just added to the DOM
• You need to manipulate the added fragment now
 • Attach event listener, manipulate its styling, whatever
• Most of the time you’ll need to let the browser
 “catch its breath”
 • So your DOM addition is actually processed and available
   through the scripting interfaces.
Classical defer use-case
 function addAndBindForm(formMarkup) {
   $('formsContainer').insert(formMarkup);
   $('formsContainer').down('form:last-of-type').
     observe('submit', genericFormValidate);
 }

             Ouch! Likely won’t
             return your form!
 function addAndBindForm(formMarkup) {
   $('formsContainer').insert(formMarkup);
   (function() {
     $('formsContainer').down('form:last-of-type').
       observe('submit', genericFormValidate);
   }).defer();
Going AOP / Decorator with wrap

• Replacing a method with an augmented version of
 it, which means you get a reference to the former
 version.
 if (Prototype.Browser.IE) {
   // Strip handlers on newly-removed elements to prevent memory leaks
   Element.Methods.update = Element.Methods.update.wrap(
      function(proceed, element, contents) {
        Element.select(element, '*').each(Event.stopObserving);
        return proceed(element, contents);
      }
   );
 }
argumentNames

• Array of argument names for a given function
• Hackish: relies on functions’ toString() capability
 • Won’t work once packed in a name-changing way (e.g.
   ShrinkSafe)
 • Won’t work on lightened-up JS runtimes (e.g. versions of
   Opera Mobile)
• We’re using it for our $super trick
 • But we should stop, and will find another way
Ajax.Response

• Encapsulates the whole response you get
 • Headers + body
• Extracts relevant-type contents
 • responseText, responseXML, responseJSON
• “Shields” header retrieval
 • Exceptions on native fetching turn into nulls
• You get that in callbacks instead of your requester
 • API-compatible, but adds stuff
Before/after 1.6 for response analysis

           Before 1.6                          Since 1.6
   callback(requester, headerJSON)    callback(response, headerJSON)

    Watch when you’re grabbing       Properties defined only once they
           properties                           make sense
                                      headerJSON, responseJSON,
         No JSON support
                                     sanitizeJSON/evalJSON options

       Automatic JS evaluation         evalJS = false|true|force

     Property fetching can raise     Fetch wrappers return '' or null
            exceptions                       when necessary.
Content insertion

• Element.insert/wrap
 • insert now takes either a single element (bottom insertion)
  or a hash of insertions (positional keys)
 • wrap puts your element within another one (bottom
  insertion) and returns, exceptionally, the wrapper (not the
  element you called wrap on).
Positioning moved into Element

• Positioning methods in Element
 • absolutize, relativize
 • getOffsetParent
 • cumulativeScrollOffset, cumulativeOffset,
   positionedOffset, viewportOffset
 • clonePosition
• This will likely all move, with dimensioning
 methods, into a separate object in 1.6.1.
Viewport inspection

• document.viewport
 • getDimensions, getWidth, getHeight
• Also remember Element.viewportOffset
• If you cache it, you should probably listen for
 window resize events and update your cache
 accordingly.
JSON support, basic math methods

• JSON support
 • Object.toJSON
 • toJSON for Date, Array, Number, Hash, String
 • String has evalJSON, isJSON and unfilterJSON
 • As we saw, Ajax.Response had dedicated stuff
• Methodized usual math on Number
 • abs, round, ceil, floor
 • e.g. myNumber.abs(), (5.42).floor()
Safer Hash and improved serialization

• New Hash
 • Essentially we wanted you to be able to store anything
  • Functions/methods, stuff whose names clash against builtins…

 • So we stopped storing on the Hash itself and use internal
   storage
 • get/set/unset/index
• Improved form serialization
 • W3C specs by the book (buttons, null/disabled/readonly…)
More versatile grep

• Extended Enumerable#grep semantics
 • Used to toString() items and apply a regex on these
 • Now uses its argument’s match method on items
 • Backwards-compatible (RegExp.match is RegExp.test)
 • Much more versatile. Consider Selector#match…
Improved Template

• Allows deep access to interpolated object using []
 and . operators
 var speaker = {
    name: 'Christophe', age: 30,
    sessions: [
      { title: 'PDD',    time: 'Monday at 8:00am' },
      { title: 'Shiny…', time: 'Wednesday at 11:05am' }
    ]
 };

 var tpl = new Template('#{name}, #{age}, will speak #{sessions.length} time(s), 
 starting on #{sessions[0].time} about #{sessions[0].title}.');

 tpl.evaluate(speaker)
 // => quot;Christophe, 30, will speak 2 time(s), starting on Monday at 8:00am about PDDquot;
Improved Template

• Only for properties.
 • If you need method calls, equip your topmost object with a
   toTemplateReplacements() method.
 var speaker = {
    …
    toTemplateReplacements: function() {
      var scount = this.sessions.length;
      return Object.extend({
        sessionCount: scount + ' time' + (scount > 1 ? 's' : '')
      }, this);
    }
 };

 var tpl = new Template('#{name}, #{age}, will speak #{sessionCount}, starting on 
 #{sessions[0].time} about #{sessions[0].title}.');
And so much more…

• String#interpolate: one-shot templating
 '#{name} is #{age} years old'.interpolate(speaker)


• Object.isXxx
 • isElement, isArray, isHash, isFunction, isString,
  isNumber, isUndefined
• Node constants
 • Guaranteed Node namespace and node type constants, from
  ELEMENT_NODE to NOTATION_NODE
And so much more…

• Array#intersect
 [1, 2, 3, 4, 5, 6].intersect([3, 5, 7]) // => [3, 5]


• Element.identify
 • Ensure you’ve got an ID in the end
• Element.setStyle(cssString)
 • If you’re hardcoding it, can be nicer than a hash
 • Is even usually faster!
The future of Prototype
Some serious flux recently…

• 2008 has been an odd year for us
• GitHub + LightHouse + dayjob overloads = ?!?
• 1.6.0.2 was released on January 25
• 1.6.0.3 was released on… September 29!
• We’re resuming active work now…
 • On a more solid ground (back to our strong policies)
 • With more community involvement (docs/tests/code/etc.)
Prototype 1.6.0.4

• Significant bugfix / perffix release
• Backward-compatible, obviously
• General directions
 • Massive code restructuration and pattern-based cleanup
   • Most notably rewrite of DOM and Event modules

 • Dozens of pending patches scheduled for upgraded commit
 • Ideally, should release before mid-November 2008
Prototype 1.6.1

• The next 3-digit release will be awesome
• General directions*
 • Massive code restructuration and pattern-based cleanup
 • Stronger, better-quality versions of 80+ pending patches
 • More builtin custom events (e.g. content changes)
 • Ajax timeouts
 • Full-spectrum positioning/dimensioning (aka “layout”)
    lookup and modification
* As always, subject to change…
Prototype 1.6.1

• When? When, when, when, when, when?
 • Er…
 • When it’s ready?
• We’d love to ship that before 2008 is over
 • But as always, we’ll ship when it’s done
 • Still, we’re going to work our asses off. Honest.



* As always, subject to change…
Prototype 2

• “Holy XHR, they’ve changed everything!”
 • Yes, but we won’t b0rk your scripts!
• General directions:
 • Way more modular
   • As everyone won’t have to grab full payload, hitherto discarded feature
    ideas could become “official modules.”

 • Better class system (no “$super”, truer encapsulation, etc.)
 • Perhaps stop extending DOM prototypes and find an API-
   compatible way to get the same code feel
The future of script.aculo.us
Scripty2

• Currently it’s “just” effects
 • 100% new effects engine, custom events-rich
 • Debug facility lets us slow down, step through, etc.
   • Jaw-droppin’ awesome, but not quite finalized yet

• Current state on GitHub
• Coming soon:
 • 100% new drag-and-drop module
 • Behaviors module (might end up shared with Prototype 2)
Scripty2 • A few demos

• Twistory
 • http://twistori.com
• Creative Scrape
 • http://creativescrape.com
• Coming-up “Progress” for the Sunlight Foundation
 • Local demo
Shameless plug

• Fully up-to-date on Prototype 1.6
 and script.aculo.us 1.8
• Full API reference
• Tons of examples / use cases
• More content and “Neuron
 Workout” solutions at
 http://thebungeebook.net/
 http://books.pragprog.com/titles/cppsu
Fair-trade plug

• Andrew Dupont’s recent book
• An ideal complement to mine
• Tackles the APIs in a different,
 very goal-oriented way
• Just like TBB, available as
 PDF and in print


 http://apress.com/book/view/1590599195
Audience Response

Questions, guys?




                   ?
On to some tech demos and
lunch! Enjoy, everyone.

More Related Content

What's hot

AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
Eyal Vardi
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Enrique Juan de Dios
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
Brian Moschel
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
Domenic Denicola
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
Chalermpon Areepong
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
AngularJs
AngularJsAngularJs
AngularJs
syam kumar kk
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
njpst8
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
JavaScript Meetup HCMC
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
BoneyGawande
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 

What's hot (20)

AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
AngularJs
AngularJsAngularJs
AngularJs
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 

Viewers also liked

LWB486 Week 7 Copyright
LWB486 Week 7 CopyrightLWB486 Week 7 Copyright
LWB486 Week 7 Copyright
Peter Black
 
Names And Places Dutch Ca1
Names And Places Dutch Ca1Names And Places Dutch Ca1
Names And Places Dutch Ca1
christianarchy
 
In memoriam
In memoriamIn memoriam
In memoriamjmarin76
 
Thesis 15 - 21
Thesis 15 - 21Thesis 15 - 21
Thesis 15 - 21
Abram John Limpin
 
Industrialization Powerpoint
Industrialization PowerpointIndustrialization Powerpoint
Industrialization Powerpoint
acrumlish
 
Vertsol1.1
Vertsol1.1Vertsol1.1
Vertsol1.1
neferteri
 
Sidds Slideshow
Sidds SlideshowSidds Slideshow
Sidds Slideshow
siddrulez
 
Apostila massa folhada_v3_aprovado
Apostila massa folhada_v3_aprovadoApostila massa folhada_v3_aprovado
Apostila massa folhada_v3_aprovado
Walter de Carvalho Baptista
 
R Report
R ReportR Report
R Report
PrincessN
 
Realize
RealizeRealize
Realize
Amber Charles
 
ข้อมูลพรรณไม้
ข้อมูลพรรณไม้ข้อมูลพรรณไม้
ข้อมูลพรรณไม้pukesasin
 
Simplethings
SimplethingsSimplethings
Simplethings
sutrisno2629
 
Vertsol Theses3 Powerpoint Slides
Vertsol Theses3   Powerpoint SlidesVertsol Theses3   Powerpoint Slides
Vertsol Theses3 Powerpoint Slides
Francis Guison
 
Friends with Benefits: Innovative Partnerships in Public Libraries
Friends with Benefits: Innovative Partnerships in Public LibrariesFriends with Benefits: Innovative Partnerships in Public Libraries
Friends with Benefits: Innovative Partnerships in Public Libraries
Sue Lawson
 
Docker wjax2014
Docker wjax2014Docker wjax2014
Docker wjax2014
Michael Johann
 
Twitter , Relaciones a largo plazo
Twitter , Relaciones a largo plazoTwitter , Relaciones a largo plazo
Twitter , Relaciones a largo plazo
VivoenCancun
 
Presentation Ob Liana
Presentation Ob LianaPresentation Ob Liana
Presentation Ob Liana
qeqey
 
System analysis to Cellular Respiration
System analysis to Cellular RespirationSystem analysis to Cellular Respiration
System analysis to Cellular Respiration
jschmied
 
42 free web tools for start ups
42 free web tools for start ups42 free web tools for start ups
42 free web tools for start ups
Sue Lawson
 
APIdays 2015 - The State of Web API Languages
APIdays 2015 - The State of Web API LanguagesAPIdays 2015 - The State of Web API Languages
APIdays 2015 - The State of Web API Languages
Jerome Louvel
 

Viewers also liked (20)

LWB486 Week 7 Copyright
LWB486 Week 7 CopyrightLWB486 Week 7 Copyright
LWB486 Week 7 Copyright
 
Names And Places Dutch Ca1
Names And Places Dutch Ca1Names And Places Dutch Ca1
Names And Places Dutch Ca1
 
In memoriam
In memoriamIn memoriam
In memoriam
 
Thesis 15 - 21
Thesis 15 - 21Thesis 15 - 21
Thesis 15 - 21
 
Industrialization Powerpoint
Industrialization PowerpointIndustrialization Powerpoint
Industrialization Powerpoint
 
Vertsol1.1
Vertsol1.1Vertsol1.1
Vertsol1.1
 
Sidds Slideshow
Sidds SlideshowSidds Slideshow
Sidds Slideshow
 
Apostila massa folhada_v3_aprovado
Apostila massa folhada_v3_aprovadoApostila massa folhada_v3_aprovado
Apostila massa folhada_v3_aprovado
 
R Report
R ReportR Report
R Report
 
Realize
RealizeRealize
Realize
 
ข้อมูลพรรณไม้
ข้อมูลพรรณไม้ข้อมูลพรรณไม้
ข้อมูลพรรณไม้
 
Simplethings
SimplethingsSimplethings
Simplethings
 
Vertsol Theses3 Powerpoint Slides
Vertsol Theses3   Powerpoint SlidesVertsol Theses3   Powerpoint Slides
Vertsol Theses3 Powerpoint Slides
 
Friends with Benefits: Innovative Partnerships in Public Libraries
Friends with Benefits: Innovative Partnerships in Public LibrariesFriends with Benefits: Innovative Partnerships in Public Libraries
Friends with Benefits: Innovative Partnerships in Public Libraries
 
Docker wjax2014
Docker wjax2014Docker wjax2014
Docker wjax2014
 
Twitter , Relaciones a largo plazo
Twitter , Relaciones a largo plazoTwitter , Relaciones a largo plazo
Twitter , Relaciones a largo plazo
 
Presentation Ob Liana
Presentation Ob LianaPresentation Ob Liana
Presentation Ob Liana
 
System analysis to Cellular Respiration
System analysis to Cellular RespirationSystem analysis to Cellular Respiration
System analysis to Cellular Respiration
 
42 free web tools for start ups
42 free web tools for start ups42 free web tools for start ups
42 free web tools for start ups
 
APIdays 2015 - The State of Web API Languages
APIdays 2015 - The State of Web API LanguagesAPIdays 2015 - The State of Web API Languages
APIdays 2015 - The State of Web API Languages
 

Similar to What's up with Prototype and script.aculo.us?

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
guest4d57e6
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
ZendCon
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
jeresig
 
Developing for Plone using ArchGenXML / ArgoUML
Developing for Plone using ArchGenXML / ArgoUMLDeveloping for Plone using ArchGenXML / ArgoUML
Developing for Plone using ArchGenXML / ArgoUML
Jazkarta, Inc.
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
desistartups
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
Nikita Popov
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
jeresig
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
Jason Lotito
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
Marc Chung
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
Tobias Oetiker
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
Jady Yang
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
jeresig
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
Simon Willison
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
Clinton Dreisbach
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
jeresig
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
Michelangelo van Dam
 

Similar to What's up with Prototype and script.aculo.us? (20)

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
 
Developing for Plone using ArchGenXML / ArgoUML
Developing for Plone using ArchGenXML / ArgoUMLDeveloping for Plone using ArchGenXML / ArgoUML
Developing for Plone using ArchGenXML / ArgoUML
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 

Recently uploaded

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Webinar: Designing a schema for a Data Warehouse
Webinar: Designing a schema for a Data WarehouseWebinar: Designing a schema for a Data Warehouse
Webinar: Designing a schema for a Data Warehouse
Federico Razzoli
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 

Recently uploaded (20)

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Webinar: Designing a schema for a Data Warehouse
Webinar: Designing a schema for a Data WarehouseWebinar: Designing a schema for a Data Warehouse
Webinar: Designing a schema for a Data Warehouse
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 

What's up with Prototype and script.aculo.us?

  • 1. What’s up with Prototype and script.aculo.us? (Shiny things in Spinoffsland) Christophe Porteneuve CTO, Ciblo.net + Prototype Core member
  • 2. Did you guys catch our Prototype Developer Day? • That was on Monday morning • Bringing the community together • Discussing contributions (to code, to docs) • Several Prototype Core members • Large Q&A session • Awesome stuff!
  • 3. What we’re going to see • Prototype 1.6 → 1.6.0.3 • Custom events • Class system • Other various improvements • Where Prototype’s headed • Prototype 1.6.1 then 2.0 • Sprockets, PDoc • Where script.aculo.us is headed (Scripty2)
  • 5. Prototype 1.6 • “Hey, that was almost a year ago!” • Yeah, but never discussed at TAE yet (plus, 1.6.0.3 now…) • And a lot of good stuff in there! • Custom events and dom:loaded • New class system, with inheritance • New Function-related stuff • Ajax.Response • Countless other improvements and fixes
  • 6. Custom events: overview • Events our own JS code triggers • Attached to DOM nodes • Bubble like regular DOM events • Publish/subscribe model: fire/observe • Major benefits • Encapsulation (internal behaviors are not exposed) • Loose coupling (anyone can trigger/observe any event) • Ability to bubble favors event delegation
  • 7. Custom events: naming and availability • How do we tell a custom event from a native one? • The custom event’s name must have 1+ colon • e.g. dom:loaded, content:updated, effect:finished • You don’t need to “register” the event • You just observe / fire it. • Custom events available on… • Any DOM node • The document object
  • 8. Custom events: “creating” them • Just observe one somewhere in your code initComputation: function() { var target = this.element.down('.computed'), that = this; function recompute() { target.update(that.getComputedValue()); } document.observe('data:changed', recompute); }
  • 9. Custom events: triggering them • Simply call fire on the relevant DOM element new Field.Observer('edtReqTaxRate', 0.5, function(field, value) { field.fire('data:changed'); });
  • 10. Custom events: the memo property initComputation: function() { var target = this.element.down('.computed'), that = this; function recompute(e) { target.update(e && e.memo ? e.memo : that.options.value); } recompute(); document.observe('data:changed', recompute); } new Field.Observer('edtReqTaxRate', 0.5, function(field, value) { field.fire('data:changed', value); });
  • 11. Custom events: already much in style • Especially by UI-oriented third-party libraries • Lets them create a full communication scheme between their widgets with no coupling whatsoever • Prototype UI • http://prototype-ui.com • LivePipe UI (f.k.a. Control.Suite) • http://livepipe.net/
  • 12. dom:loaded • Our first “standard” custom event • Triggers right after DOM load • So just forget Event.observe(window, 'load', initPage); • And use document.observe('dom:loaded', initPage);
  • 13. A note about stopObserving • You can make partial calls now • Omit the handler myEditor.stopObserving('change'); • All handlers for this event on this element • Omit the event too myEditor.stopObserving(); • All handlers on all events on this element • Easier cleanup
  • 14. More Event goodness • Guaranteed even methods and properties • relatedTarget, pageX, pageY • stopPropagation(), preventDefault(), stopped • Click detection • isLeftClick(), isMiddleClick(), isRightClick() • Pointer position • pointer(), pointerX(), pointerY()
  • 15. A note on event binding • Pre-1.6, handlers were “unbound” by default • Unless you had bound them explicitly, they’d end up using the window scope • Starting with 1.6, handlers are bound to the subject of your observe call by default • If you bound them explicitly, as always, that prior binding will be retained.
  • 16. New class system • The idea: ease up traditional OOP constructs and behaviors • Inheritance • Mix-ins • Method overriding with access to inherited version • Backward-compatible API
  • 17. Ye Olde Class var MyClass = Class.create({ initialize: function(…) { • Key issues: // “Constructor” code here • initialize required, }, even if empty publicMethod1: function(…) { }, • Can’t give a parent class … }); • Can’t override methods easily
  • 18. The new class syntax var MyClass = Class.create([parentClass, ][mixIns…, ]{ [initialize: function(…) { … },] publicMethod1: …, … }) • We can provide a single parent class • We then handle the prototype chaining for it • We can provide 1+ “mixins” (modules) • Bunches of methods that get blended in the prototype. • initialize is optional (an empty one will fill in)
  • 19. Inheritance becomes a breeze var XMLParser = Class.create({ initialize: function(source) { … }, … }); var XHTMLParser = Class.create(XMLParser, { … }); var AtomParser = Class.create(XMLParser, { … });
  • 20. Free stuff you get • Every instance has a constructor • Every class has a superclass and subclasses XMLParser.superclass // => null XHTMLParser.superclass // => XMLParser AtomParser.superclass // => XMLParser XMLParser.subclasses // => [XHTMLParser, AtomParser] var parser = new XHTMLParser(someXHTMLSource); parser.constructor // => XHTMLParser parser.constructor.superclass // => XMLParser
  • 21. Mixing in modules • A module is just a bag of properties/methods • You can mix as many of those as you want at class creation time. var FeedAnalyzer = { // methods… }; … var AtomParser = Class.create(XMLParser, FeedAnalyzer, MarkupFixer, StandardNamespaceHandler, { … });
  • 22. Class methods • These are just methods on the Class object itself, so we can resort to good ol’ Object.extend. var MyGenericClassMethods = { // methods… }; … Object.extend(AtomParser, MyGenericClassMethods); Object.extend(AtomParser, { adHocMethod1: …, adHocMethod2: …, … });
  • 23. Adding methods post-declaration • Every class has a addMethods method that mixes anything module-like in. • It’s actually used on your modules (and custom methods) at creation time. var UberCoolMethodsIGotJustNow = { leverageMicroFormats: …, turnIntoiPhoneUIs: …, turnIntoUniversalWidgets: … }; AtomParser.addMethods(UberCoolMethodsIGotJustNow);
  • 24. Accessing overridden methods • Insert a $super first argument. That’s it. var XMLParser = Class.create({ initialize: function(source) { … }, … }); var AtomParser = Class.create({ initialize: function($super, source, options) { $super(source); // Handle options }, … });
  • 25. Function-fu • Prototype 1.6 introduced a lot of new methods on function so you can reduce custom anonymous wrappers and go wild (but reasonable) with AOP • curry, rescuer of useless binds • delay and defer, because patience is a virtue • wrap, because AOP / Decorator can rock • argumentNames (aka Hackish The First)
  • 26. Spicying up your code with curry • You know how you always use bind(null,…) just because you need partial application? $('preview').observe('mousewheel:up', shiftZoom.bind(null, 125)); $('preview').observe('mousewheel:down', shiftZoom.bind(null, 80)); • Don’t do it. • That’s what curry is for: $('preview').observe('mousewheel:up', shiftZoom.curry(125)); $('preview').observe('mousewheel:down', shiftZoom.curry(80));
  • 27. curry vs. bind • You should use bind when… • You actually need to bind (set the semantics of this) • It doesn’t matter whether you want to pre-fill arguments! • You should use curry when… • You need to pre-fill arguments • And you don’t care about the binding, or more specifically don’t want to change it.
  • 28. Deferring execution: delay and defer • Schedule execution of a snippet of JS for later • Either a specific time later • Or ASAP—typically right after the DOM got a moment to breathe in your recent updates • function.delay(seconds) • defer is the “ASAP” case, and is just… • delay.curry(0.1) :-) • Essentially works because of single-threadedness
  • 29. Classical defer use-case • You just added to the DOM • You need to manipulate the added fragment now • Attach event listener, manipulate its styling, whatever • Most of the time you’ll need to let the browser “catch its breath” • So your DOM addition is actually processed and available through the scripting interfaces.
  • 30. Classical defer use-case function addAndBindForm(formMarkup) { $('formsContainer').insert(formMarkup); $('formsContainer').down('form:last-of-type'). observe('submit', genericFormValidate); } Ouch! Likely won’t return your form! function addAndBindForm(formMarkup) { $('formsContainer').insert(formMarkup); (function() { $('formsContainer').down('form:last-of-type'). observe('submit', genericFormValidate); }).defer();
  • 31. Going AOP / Decorator with wrap • Replacing a method with an augmented version of it, which means you get a reference to the former version. if (Prototype.Browser.IE) { // Strip handlers on newly-removed elements to prevent memory leaks Element.Methods.update = Element.Methods.update.wrap( function(proceed, element, contents) { Element.select(element, '*').each(Event.stopObserving); return proceed(element, contents); } ); }
  • 32. argumentNames • Array of argument names for a given function • Hackish: relies on functions’ toString() capability • Won’t work once packed in a name-changing way (e.g. ShrinkSafe) • Won’t work on lightened-up JS runtimes (e.g. versions of Opera Mobile) • We’re using it for our $super trick • But we should stop, and will find another way
  • 33. Ajax.Response • Encapsulates the whole response you get • Headers + body • Extracts relevant-type contents • responseText, responseXML, responseJSON • “Shields” header retrieval • Exceptions on native fetching turn into nulls • You get that in callbacks instead of your requester • API-compatible, but adds stuff
  • 34. Before/after 1.6 for response analysis Before 1.6 Since 1.6 callback(requester, headerJSON) callback(response, headerJSON) Watch when you’re grabbing Properties defined only once they properties make sense headerJSON, responseJSON, No JSON support sanitizeJSON/evalJSON options Automatic JS evaluation evalJS = false|true|force Property fetching can raise Fetch wrappers return '' or null exceptions when necessary.
  • 35. Content insertion • Element.insert/wrap • insert now takes either a single element (bottom insertion) or a hash of insertions (positional keys) • wrap puts your element within another one (bottom insertion) and returns, exceptionally, the wrapper (not the element you called wrap on).
  • 36. Positioning moved into Element • Positioning methods in Element • absolutize, relativize • getOffsetParent • cumulativeScrollOffset, cumulativeOffset, positionedOffset, viewportOffset • clonePosition • This will likely all move, with dimensioning methods, into a separate object in 1.6.1.
  • 37. Viewport inspection • document.viewport • getDimensions, getWidth, getHeight • Also remember Element.viewportOffset • If you cache it, you should probably listen for window resize events and update your cache accordingly.
  • 38. JSON support, basic math methods • JSON support • Object.toJSON • toJSON for Date, Array, Number, Hash, String • String has evalJSON, isJSON and unfilterJSON • As we saw, Ajax.Response had dedicated stuff • Methodized usual math on Number • abs, round, ceil, floor • e.g. myNumber.abs(), (5.42).floor()
  • 39. Safer Hash and improved serialization • New Hash • Essentially we wanted you to be able to store anything • Functions/methods, stuff whose names clash against builtins… • So we stopped storing on the Hash itself and use internal storage • get/set/unset/index • Improved form serialization • W3C specs by the book (buttons, null/disabled/readonly…)
  • 40. More versatile grep • Extended Enumerable#grep semantics • Used to toString() items and apply a regex on these • Now uses its argument’s match method on items • Backwards-compatible (RegExp.match is RegExp.test) • Much more versatile. Consider Selector#match…
  • 41. Improved Template • Allows deep access to interpolated object using [] and . operators var speaker = { name: 'Christophe', age: 30, sessions: [ { title: 'PDD', time: 'Monday at 8:00am' }, { title: 'Shiny…', time: 'Wednesday at 11:05am' } ] }; var tpl = new Template('#{name}, #{age}, will speak #{sessions.length} time(s), starting on #{sessions[0].time} about #{sessions[0].title}.'); tpl.evaluate(speaker) // => quot;Christophe, 30, will speak 2 time(s), starting on Monday at 8:00am about PDDquot;
  • 42. Improved Template • Only for properties. • If you need method calls, equip your topmost object with a toTemplateReplacements() method. var speaker = { … toTemplateReplacements: function() { var scount = this.sessions.length; return Object.extend({ sessionCount: scount + ' time' + (scount > 1 ? 's' : '') }, this); } }; var tpl = new Template('#{name}, #{age}, will speak #{sessionCount}, starting on #{sessions[0].time} about #{sessions[0].title}.');
  • 43. And so much more… • String#interpolate: one-shot templating '#{name} is #{age} years old'.interpolate(speaker) • Object.isXxx • isElement, isArray, isHash, isFunction, isString, isNumber, isUndefined • Node constants • Guaranteed Node namespace and node type constants, from ELEMENT_NODE to NOTATION_NODE
  • 44. And so much more… • Array#intersect [1, 2, 3, 4, 5, 6].intersect([3, 5, 7]) // => [3, 5] • Element.identify • Ensure you’ve got an ID in the end • Element.setStyle(cssString) • If you’re hardcoding it, can be nicer than a hash • Is even usually faster!
  • 45. The future of Prototype
  • 46. Some serious flux recently… • 2008 has been an odd year for us • GitHub + LightHouse + dayjob overloads = ?!? • 1.6.0.2 was released on January 25 • 1.6.0.3 was released on… September 29! • We’re resuming active work now… • On a more solid ground (back to our strong policies) • With more community involvement (docs/tests/code/etc.)
  • 47. Prototype 1.6.0.4 • Significant bugfix / perffix release • Backward-compatible, obviously • General directions • Massive code restructuration and pattern-based cleanup • Most notably rewrite of DOM and Event modules • Dozens of pending patches scheduled for upgraded commit • Ideally, should release before mid-November 2008
  • 48. Prototype 1.6.1 • The next 3-digit release will be awesome • General directions* • Massive code restructuration and pattern-based cleanup • Stronger, better-quality versions of 80+ pending patches • More builtin custom events (e.g. content changes) • Ajax timeouts • Full-spectrum positioning/dimensioning (aka “layout”) lookup and modification * As always, subject to change…
  • 49. Prototype 1.6.1 • When? When, when, when, when, when? • Er… • When it’s ready? • We’d love to ship that before 2008 is over • But as always, we’ll ship when it’s done • Still, we’re going to work our asses off. Honest. * As always, subject to change…
  • 50. Prototype 2 • “Holy XHR, they’ve changed everything!” • Yes, but we won’t b0rk your scripts! • General directions: • Way more modular • As everyone won’t have to grab full payload, hitherto discarded feature ideas could become “official modules.” • Better class system (no “$super”, truer encapsulation, etc.) • Perhaps stop extending DOM prototypes and find an API- compatible way to get the same code feel
  • 51. The future of script.aculo.us
  • 52. Scripty2 • Currently it’s “just” effects • 100% new effects engine, custom events-rich • Debug facility lets us slow down, step through, etc. • Jaw-droppin’ awesome, but not quite finalized yet • Current state on GitHub • Coming soon: • 100% new drag-and-drop module • Behaviors module (might end up shared with Prototype 2)
  • 53. Scripty2 • A few demos • Twistory • http://twistori.com • Creative Scrape • http://creativescrape.com • Coming-up “Progress” for the Sunlight Foundation • Local demo
  • 54. Shameless plug • Fully up-to-date on Prototype 1.6 and script.aculo.us 1.8 • Full API reference • Tons of examples / use cases • More content and “Neuron Workout” solutions at http://thebungeebook.net/ http://books.pragprog.com/titles/cppsu
  • 55. Fair-trade plug • Andrew Dupont’s recent book • An ideal complement to mine • Tackles the APIs in a different, very goal-oriented way • Just like TBB, available as PDF and in print http://apress.com/book/view/1590599195
  • 57. On to some tech demos and lunch! Enjoy, everyone.