SlideShare uma empresa Scribd logo
1 de 57
Baixar para ler offline
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.

Mais conteúdo relacionado

Mais procurados

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 ServicesRainer Stropek
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS AnimationsEyal Vardi
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
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.0Eyal Vardi
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategiesnjpst8
 
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 & UXJWORKS 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 그리고 angular2Jeado Ko
 

Mais procurados (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
 

Destaque

LWB486 Week 7 Copyright
LWB486 Week 7 CopyrightLWB486 Week 7 Copyright
LWB486 Week 7 CopyrightPeter Black
 
Names And Places Dutch Ca1
Names And Places Dutch Ca1Names And Places Dutch Ca1
Names And Places Dutch Ca1christianarchy
 
In memoriam
In memoriamIn memoriam
In memoriamjmarin76
 
Industrialization Powerpoint
Industrialization PowerpointIndustrialization Powerpoint
Industrialization Powerpointacrumlish
 
Sidds Slideshow
Sidds SlideshowSidds Slideshow
Sidds Slideshowsiddrulez
 
ข้อมูลพรรณไม้
ข้อมูลพรรณไม้ข้อมูลพรรณไม้
ข้อมูลพรรณไม้pukesasin
 
Vertsol Theses3 Powerpoint Slides
Vertsol Theses3   Powerpoint SlidesVertsol Theses3   Powerpoint Slides
Vertsol Theses3 Powerpoint SlidesFrancis 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 LibrariesSue Lawson
 
Twitter , Relaciones a largo plazo
Twitter , Relaciones a largo plazoTwitter , Relaciones a largo plazo
Twitter , Relaciones a largo plazoVivoenCancun
 
Presentation Ob Liana
Presentation Ob LianaPresentation Ob Liana
Presentation Ob Lianaqeqey
 
System analysis to Cellular Respiration
System analysis to Cellular RespirationSystem analysis to Cellular Respiration
System analysis to Cellular Respirationjschmied
 
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 upsSue 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 LanguagesJerome Louvel
 

Destaque (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
 

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

Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
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 betterZendCon
 
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 / ArgoUMLJazkarta, Inc.
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Jason Lotito
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsTobias Oetiker
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuffjeresig
 
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 youSimon Willison
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 

Semelhante a 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
 

Último

Build Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQL
Build Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQLBuild Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQL
Build Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQLHostedbyConfluent
 
Real-time Geospatial Aircraft Monitoring Using Apache Kafka
Real-time Geospatial Aircraft Monitoring Using Apache KafkaReal-time Geospatial Aircraft Monitoring Using Apache Kafka
Real-time Geospatial Aircraft Monitoring Using Apache KafkaHostedbyConfluent
 
Bridge to the Future: Migrating to KRaft
Bridge to the Future: Migrating to KRaftBridge to the Future: Migrating to KRaft
Bridge to the Future: Migrating to KRaftHostedbyConfluent
 
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024BookNet Canada
 
Aggregating Ad Events with Kafka Streams and Interactive Queries at Invidi
Aggregating Ad Events with Kafka Streams and Interactive Queries at InvidiAggregating Ad Events with Kafka Streams and Interactive Queries at Invidi
Aggregating Ad Events with Kafka Streams and Interactive Queries at InvidiHostedbyConfluent
 
Modifying Your SQL Streaming Queries on the Fly: The Impossible Trinity
Modifying Your SQL Streaming Queries on the Fly: The Impossible TrinityModifying Your SQL Streaming Queries on the Fly: The Impossible Trinity
Modifying Your SQL Streaming Queries on the Fly: The Impossible TrinityHostedbyConfluent
 
THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023
THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023
THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023Joshua Flannery
 
Dynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationDynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationBuild Intuit
 
How Do You Query a Stream? | Kafka Summit London
How Do You Query a Stream? | Kafka Summit LondonHow Do You Query a Stream? | Kafka Summit London
How Do You Query a Stream? | Kafka Summit LondonHostedbyConfluent
 
Beyond Tiered Storage: Serverless Kafka with No Local Disks
Beyond Tiered Storage: Serverless Kafka with No Local DisksBeyond Tiered Storage: Serverless Kafka with No Local Disks
Beyond Tiered Storage: Serverless Kafka with No Local DisksHostedbyConfluent
 
DS Lesson 2 - Subsets, Supersets and Power Set.pdf
DS Lesson 2 - Subsets, Supersets and Power Set.pdfDS Lesson 2 - Subsets, Supersets and Power Set.pdf
DS Lesson 2 - Subsets, Supersets and Power Set.pdfROWELL MARQUINA
 
The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...
The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...
The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...HostedbyConfluent
 
Women in Automation 2024: Technical session - Get your career started in auto...
Women in Automation 2024: Technical session - Get your career started in auto...Women in Automation 2024: Technical session - Get your career started in auto...
Women in Automation 2024: Technical session - Get your career started in auto...DianaGray10
 
BODYPACK DIGITAL TECHNOLOGY STACK - 2024
BODYPACK DIGITAL TECHNOLOGY STACK - 2024BODYPACK DIGITAL TECHNOLOGY STACK - 2024
BODYPACK DIGITAL TECHNOLOGY STACK - 2024Andri H.
 
Building a Self-Service Stream Processing Portal: How And Why
Building a Self-Service Stream Processing Portal: How And WhyBuilding a Self-Service Stream Processing Portal: How And Why
Building a Self-Service Stream Processing Portal: How And WhyHostedbyConfluent
 
Event-Driven Microservices: Back to the Basics
Event-Driven Microservices: Back to the BasicsEvent-Driven Microservices: Back to the Basics
Event-Driven Microservices: Back to the BasicsHostedbyConfluent
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactivestartupro
 
Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...
Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...
Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...HostedbyConfluent
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
Apache Flink: Building a Company-wide Self-service Streaming Data Platform
Apache Flink: Building a Company-wide Self-service Streaming Data PlatformApache Flink: Building a Company-wide Self-service Streaming Data Platform
Apache Flink: Building a Company-wide Self-service Streaming Data PlatformHostedbyConfluent
 

Último (20)

Build Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQL
Build Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQLBuild Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQL
Build Copilots on Streaming Data with Generative AI, Kafka Streams and Flink SQL
 
Real-time Geospatial Aircraft Monitoring Using Apache Kafka
Real-time Geospatial Aircraft Monitoring Using Apache KafkaReal-time Geospatial Aircraft Monitoring Using Apache Kafka
Real-time Geospatial Aircraft Monitoring Using Apache Kafka
 
Bridge to the Future: Migrating to KRaft
Bridge to the Future: Migrating to KRaftBridge to the Future: Migrating to KRaft
Bridge to the Future: Migrating to KRaft
 
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
 
Aggregating Ad Events with Kafka Streams and Interactive Queries at Invidi
Aggregating Ad Events with Kafka Streams and Interactive Queries at InvidiAggregating Ad Events with Kafka Streams and Interactive Queries at Invidi
Aggregating Ad Events with Kafka Streams and Interactive Queries at Invidi
 
Modifying Your SQL Streaming Queries on the Fly: The Impossible Trinity
Modifying Your SQL Streaming Queries on the Fly: The Impossible TrinityModifying Your SQL Streaming Queries on the Fly: The Impossible Trinity
Modifying Your SQL Streaming Queries on the Fly: The Impossible Trinity
 
THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023
THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023
THE STATE OF STARTUP ECOSYSTEM - INDIA x JAPAN 2023
 
Dynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientationDynamical Context introduction word sensibility orientation
Dynamical Context introduction word sensibility orientation
 
How Do You Query a Stream? | Kafka Summit London
How Do You Query a Stream? | Kafka Summit LondonHow Do You Query a Stream? | Kafka Summit London
How Do You Query a Stream? | Kafka Summit London
 
Beyond Tiered Storage: Serverless Kafka with No Local Disks
Beyond Tiered Storage: Serverless Kafka with No Local DisksBeyond Tiered Storage: Serverless Kafka with No Local Disks
Beyond Tiered Storage: Serverless Kafka with No Local Disks
 
DS Lesson 2 - Subsets, Supersets and Power Set.pdf
DS Lesson 2 - Subsets, Supersets and Power Set.pdfDS Lesson 2 - Subsets, Supersets and Power Set.pdf
DS Lesson 2 - Subsets, Supersets and Power Set.pdf
 
The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...
The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...
The Streaming Data Lake - What Do KIP-405 and KIP-833 Mean for Your Larger Da...
 
Women in Automation 2024: Technical session - Get your career started in auto...
Women in Automation 2024: Technical session - Get your career started in auto...Women in Automation 2024: Technical session - Get your career started in auto...
Women in Automation 2024: Technical session - Get your career started in auto...
 
BODYPACK DIGITAL TECHNOLOGY STACK - 2024
BODYPACK DIGITAL TECHNOLOGY STACK - 2024BODYPACK DIGITAL TECHNOLOGY STACK - 2024
BODYPACK DIGITAL TECHNOLOGY STACK - 2024
 
Building a Self-Service Stream Processing Portal: How And Why
Building a Self-Service Stream Processing Portal: How And WhyBuilding a Self-Service Stream Processing Portal: How And Why
Building a Self-Service Stream Processing Portal: How And Why
 
Event-Driven Microservices: Back to the Basics
Event-Driven Microservices: Back to the BasicsEvent-Driven Microservices: Back to the Basics
Event-Driven Microservices: Back to the Basics
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactive
 
Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...
Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...
Leveraging Tiered Storage in Strimzi-Operated Kafka for Cost-Effective Stream...
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
Apache Flink: Building a Company-wide Self-service Streaming Data Platform
Apache Flink: Building a Company-wide Self-service Streaming Data PlatformApache Flink: Building a Company-wide Self-service Streaming Data Platform
Apache Flink: Building a Company-wide Self-service Streaming Data Platform
 

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.