SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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 a 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
 

Último

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 

Último (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
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
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

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