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

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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