SlideShare a Scribd company logo
1 of 16
Download to read offline
SILVERSTRIPE CMS
              JAVASCRIPT REFACTORING
                         The jsparty is over!




Friday, 28 August 2009
SCOPE
              • JavaScript    library upgrade, no more forks

              • CMS JavaScript cleanup
                Rewrite in jQuery where feasible

              • CMS      PHP Controller simplification

              • More      solid UI components with jQuery UI and plugins

              • CSS Architecture     for easier customization

              • Not      a large-scale CMS redesign
Friday, 28 August 2009
LIBRARIES

    • Prototype           1.4rc3 to jQuery 1.3

    • Random             UI code and ancient libs to jQuery UI 1.7

    • Custom             behaviour.js to jQuery.concrete

    • External   libraries managed by Piston (piston.rubyforge.org/)
        instead of svn:externals


Friday, 28 August 2009
GOODBYE JSPARTY
         • Merged   external libraries
             to cms/thirdparty and sapphire/thirdparty




Friday, 28 August 2009
THE DARK AGES

                         function hover_over() {
                           Element.addClassName(this, 'over');
                         }
                         function hover_out() {
                           Element.removeClassName(this, 'over');
                         }

                         hover_behaviour = {
                           onmouseover : hover_over,
                           onmouseout : hover_out
                         }
                         jsparty/hover.js




Friday, 28 August 2009
THE DARK AGES
                 class LeftAndMain {
            // ...
                public function returnItemToUser($p) {
                   // ...
                   $response = <<<JS
                     var tree = $('sitetree');
                     var newNode = tree.createTreeNode("$id", "$treeTitle", "{$p->class}{$hasChildren}
            {$singleInstanceCSSClass}");
                     node = tree.getTreeNodeByIdx($parentID);
                     if(!node) {
                       node = tree.getTreeNodeByIdx(0);
                     }
                     node.open();
                     node.appendTreeNode(newNode);
                     newNode.selectTreeNode();
            JS;
                   FormResponse::add($response);
                   FormResponse::add($this->hideSingleInstanceOnlyFromCreateFieldJS($p));

                     return FormResponse::respond();
                }
            }

          cms/code/LeftAndMain.php (excerpt)




Friday, 28 August 2009
BEST PRACTICES


                         • Don’t   claim global properties

                         • Assume    element collections

                         • Encapsulate: jQuery.concrete, jQuery   plugin,
                          jQueryUI widget (in this order)



Friday, 28 August 2009
ENCAPSULATE: EXAMPLE
                                    Simple Highlight jQuery Plugin
                         // create closure
                         (function($) {
                           // plugin definition
                           $.fn.hilight = function(options) {
                              // build main options before element iteration
                              var opts = $.extend({}, $.fn.hilight.defaults, options);
                              // iterate and reformat each matched element
                              return this.each(function() {
                                $this = $(this);
                                // build element specific options
                                var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
                                // update element styles
                                $this.css({backgroundColor: o.background,color: o.foreground});
                              });
                           };
                           // plugin defaults
                           $.fn.hilight.defaults = {foreground: "red",background: "yellow"};
                         // end of closure
                         })(jQuery);




Friday, 28 August 2009
BEST PRACTICES


                         • Useplain HTML, jQuery.data() and
                          jQuery.metadata to encode initial state
                          and (some) configuration

                         • Better
                                than building “object cathedrals” in
                          most cases



Friday, 28 August 2009
STATE: EXAMPLE
                              Simple Form Changetracking

    State in CSS                 $('form :input').bind('change', function(e) {
                                   $(this.form).addClass('isChanged');
                                 });
    properties                   $('form').bind('submit', function(e) {
                                   if($(this).hasClass('isChanged')) return false;
                                 });




                                 $('form :input').bind('change', function(e) {

    State in DOM                   $(this.form).data('isChanged', true);
                                 });
                                 $('form').bind('submit', function(e) {
    (through jQuery.data())        if($(this).data('isChanged')) return false;
                                 });




Friday, 28 August 2009
BEST PRACTICES
    • Ajax               responses should default to HTML
        Makes it easier to write unobtrusive markup and use SilverStripe templating

    • Use           HTTP metadata to transport state and additional data
        Example: 404 HTTP status code to return “Not Found”
        Example: Custom “X-Status” header for more detailed UI status

    • Return               JSON if HTML is not feasible
        Example: Update several tree nodes after CMS batch actions
        Alternative: Inspect the returned DOM for more structured data like id attributes

    • For AJAX               and parameter transmission, <form> is your friend

Friday, 28 August 2009
AJAX: EXAMPLE
                   Simple Serverside Autocomplete for Page Titles
                          <form action"#">
                            <div class="autocomplete {url:'MyController/autocomplete'}">
                              <input type="text" name="title" />
                              <div class="results" style="display: none;">
                            </div>
                            <input type="submit" value="action_autocomplete" />
                          </form>
                          MyController.ss


                                                                                       Using jQuery.metadata,
                                                                            but could be a plain SilverStripe Form as well


                                            <ul>
                                            <% control Results %>
                                              <li id="Result-$ID">$Title</li>
                                            <% end_control %>
                                            </ul>
                                            AutoComplete.ss




Friday, 28 August 2009
AJAX: EXAMPLE

                         class MyController {
                           function autocomplete($request) {
                             $SQL_title = Convert::raw2sql($request->getVar('title'));
                             $results = DataObject::get("Page", "Title LIKE '%$SQL_title%'");
                             if(!$results) return new HTTPResponse("Not found", 404);

                                 // Use HTTPResponse to pass custom status messages
                                 $this->response->setStatusCode(200, "Found " . $results->Count() . " elements");

                                 // render all results with a custom template
                                 $vd = new ViewableData();
                                 return $vd->customise(array(
                                   "Results" => $results
                                 ))->renderWith('AutoComplete');
                             }
                         }
                         MyController.php




Friday, 28 August 2009
AJAX: EXAMPLE

                         $('.autocomplete input').live('change', function() {
                           var resultsEl = $(this).siblings('.results');
                           resultsEl.load(
                              // get form action, using the jQuery.metadata plugin
                              $(this).parent().metadata().url,
                              // submit all form values
                              $(this.form).serialize(),
                              // callback after data is loaded
                              function(data, status) {
                                resultsEl.show();
                                // optional: get all record IDs from the new HTML
                                var ids = jQuery('.results').find('li').map(function() {
                                  return $(this).attr('id').replace(/Record-/,'');
                                });
                              }
                           );
                         });
                         MyController.js




Friday, 28 August 2009
BEST PRACTICES

    • Use           events and observation for component communication

    • Use           composition for synchronous, two-way communicatoin

    • Use           callbacks to allow for customization

    • Don’t              overuse prototypical inheritance and pseudo-classes

    • Only   expose public APIs where necessary
        (through jQuery.concrete)

Friday, 28 August 2009
RESOURCES

                              Documentation (unreleased)
                          http://doc.silverstripe.com/doku.php?id=2.4:javascript



                         Source (unreleased, pre 2.4 alpha)
                          http://github.com/chillu/sapphire/tree/jsrewrite

                             http://github.com/chillu/cms/tree/jsrewrite



Friday, 28 August 2009

More Related Content

What's hot

JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineRaimonds Simanovskis
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Roy Yu
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyIgor Napierala
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript ApplicationsThe Rolling Scopes
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript TestingThomas Fuchs
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mochaRevath S Kumar
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesMarcello Duarte
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 

What's hot (20)

JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
RSpec
RSpecRSpec
RSpec
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
Excellent
ExcellentExcellent
Excellent
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript Testing
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examples
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 

Similar to SilverStripe CMS JavaScript Refactoring

jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowkatbailey
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowWork at Play
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETJames Johnson
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQueryRemy Sharp
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes senseEldar Djafarov
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery PluginsJörn Zaefferer
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 

Similar to SilverStripe CMS JavaScript Refactoring (20)

jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
J query1
J query1J query1
J query1
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
React.js or why DOM finally makes sense
React.js or why DOM finally makes senseReact.js or why DOM finally makes sense
React.js or why DOM finally makes sense
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 

Recently uploaded

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Recently uploaded (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

SilverStripe CMS JavaScript Refactoring

  • 1. SILVERSTRIPE CMS JAVASCRIPT REFACTORING The jsparty is over! Friday, 28 August 2009
  • 2. SCOPE • JavaScript library upgrade, no more forks • CMS JavaScript cleanup Rewrite in jQuery where feasible • CMS PHP Controller simplification • More solid UI components with jQuery UI and plugins • CSS Architecture for easier customization • Not a large-scale CMS redesign Friday, 28 August 2009
  • 3. LIBRARIES • Prototype 1.4rc3 to jQuery 1.3 • Random UI code and ancient libs to jQuery UI 1.7 • Custom behaviour.js to jQuery.concrete • External libraries managed by Piston (piston.rubyforge.org/) instead of svn:externals Friday, 28 August 2009
  • 4. GOODBYE JSPARTY • Merged external libraries to cms/thirdparty and sapphire/thirdparty Friday, 28 August 2009
  • 5. THE DARK AGES function hover_over() { Element.addClassName(this, 'over'); } function hover_out() { Element.removeClassName(this, 'over'); } hover_behaviour = { onmouseover : hover_over, onmouseout : hover_out } jsparty/hover.js Friday, 28 August 2009
  • 6. THE DARK AGES class LeftAndMain { // ... public function returnItemToUser($p) { // ... $response = <<<JS var tree = $('sitetree'); var newNode = tree.createTreeNode("$id", "$treeTitle", "{$p->class}{$hasChildren} {$singleInstanceCSSClass}"); node = tree.getTreeNodeByIdx($parentID); if(!node) { node = tree.getTreeNodeByIdx(0); } node.open(); node.appendTreeNode(newNode); newNode.selectTreeNode(); JS; FormResponse::add($response); FormResponse::add($this->hideSingleInstanceOnlyFromCreateFieldJS($p)); return FormResponse::respond(); } } cms/code/LeftAndMain.php (excerpt) Friday, 28 August 2009
  • 7. BEST PRACTICES • Don’t claim global properties • Assume element collections • Encapsulate: jQuery.concrete, jQuery plugin, jQueryUI widget (in this order) Friday, 28 August 2009
  • 8. ENCAPSULATE: EXAMPLE Simple Highlight jQuery Plugin // create closure (function($) { // plugin definition $.fn.hilight = function(options) { // build main options before element iteration var opts = $.extend({}, $.fn.hilight.defaults, options); // iterate and reformat each matched element return this.each(function() { $this = $(this); // build element specific options var o = $.meta ? $.extend({}, opts, $this.data()) : opts; // update element styles $this.css({backgroundColor: o.background,color: o.foreground}); }); }; // plugin defaults $.fn.hilight.defaults = {foreground: "red",background: "yellow"}; // end of closure })(jQuery); Friday, 28 August 2009
  • 9. BEST PRACTICES • Useplain HTML, jQuery.data() and jQuery.metadata to encode initial state and (some) configuration • Better than building “object cathedrals” in most cases Friday, 28 August 2009
  • 10. STATE: EXAMPLE Simple Form Changetracking State in CSS $('form :input').bind('change', function(e) { $(this.form).addClass('isChanged'); }); properties $('form').bind('submit', function(e) { if($(this).hasClass('isChanged')) return false; }); $('form :input').bind('change', function(e) { State in DOM $(this.form).data('isChanged', true); }); $('form').bind('submit', function(e) { (through jQuery.data()) if($(this).data('isChanged')) return false; }); Friday, 28 August 2009
  • 11. BEST PRACTICES • Ajax responses should default to HTML Makes it easier to write unobtrusive markup and use SilverStripe templating • Use HTTP metadata to transport state and additional data Example: 404 HTTP status code to return “Not Found” Example: Custom “X-Status” header for more detailed UI status • Return JSON if HTML is not feasible Example: Update several tree nodes after CMS batch actions Alternative: Inspect the returned DOM for more structured data like id attributes • For AJAX and parameter transmission, <form> is your friend Friday, 28 August 2009
  • 12. AJAX: EXAMPLE Simple Serverside Autocomplete for Page Titles <form action"#"> <div class="autocomplete {url:'MyController/autocomplete'}"> <input type="text" name="title" /> <div class="results" style="display: none;"> </div> <input type="submit" value="action_autocomplete" /> </form> MyController.ss Using jQuery.metadata, but could be a plain SilverStripe Form as well <ul> <% control Results %> <li id="Result-$ID">$Title</li> <% end_control %> </ul> AutoComplete.ss Friday, 28 August 2009
  • 13. AJAX: EXAMPLE class MyController { function autocomplete($request) { $SQL_title = Convert::raw2sql($request->getVar('title')); $results = DataObject::get("Page", "Title LIKE '%$SQL_title%'"); if(!$results) return new HTTPResponse("Not found", 404); // Use HTTPResponse to pass custom status messages $this->response->setStatusCode(200, "Found " . $results->Count() . " elements"); // render all results with a custom template $vd = new ViewableData(); return $vd->customise(array( "Results" => $results ))->renderWith('AutoComplete'); } } MyController.php Friday, 28 August 2009
  • 14. AJAX: EXAMPLE $('.autocomplete input').live('change', function() { var resultsEl = $(this).siblings('.results'); resultsEl.load( // get form action, using the jQuery.metadata plugin $(this).parent().metadata().url, // submit all form values $(this.form).serialize(), // callback after data is loaded function(data, status) { resultsEl.show(); // optional: get all record IDs from the new HTML var ids = jQuery('.results').find('li').map(function() { return $(this).attr('id').replace(/Record-/,''); }); } ); }); MyController.js Friday, 28 August 2009
  • 15. BEST PRACTICES • Use events and observation for component communication • Use composition for synchronous, two-way communicatoin • Use callbacks to allow for customization • Don’t overuse prototypical inheritance and pseudo-classes • Only expose public APIs where necessary (through jQuery.concrete) Friday, 28 August 2009
  • 16. RESOURCES Documentation (unreleased) http://doc.silverstripe.com/doku.php?id=2.4:javascript Source (unreleased, pre 2.4 alpha) http://github.com/chillu/sapphire/tree/jsrewrite http://github.com/chillu/cms/tree/jsrewrite Friday, 28 August 2009