SlideShare une entreprise Scribd logo
1  sur  67
Télécharger pour lire hors ligne
Rails is not just
      Ruby
Marco Otte-Witte


Software Engineer, Consultant, Trainer
         http://simplabs.com


            Open Source
     http://github.com/marcoow
     http://github.com/simplabs
JavaScript is
   serious
  Business!
It‘s not just
adding lib after
  lib after lib!
Give your
 JavaScript the
same love your
   Ruby code
     gets!
Know your
  tools!
Know your tools!



var inputs = $$('input');
for (var i = 0; i < inputs.length; i++) {
  alert(inputs[i].name);
}
Know your tools!




              X
var inputs = $$('input');
for (var i = 0; i < inputs.length; i++) {

}
  alert(inputs[i].name);
Know your tools!
Protoype.js
$$('input').each(function(input) {
  alert(input.name);
});

jQuery
$.each('input', function() {
  alert(this.name);
});
Know your tools!
function setupPage() {
  $('userName').update(
     readUserName();
  );
}

function readUserName() {
  //read user's name from cookie
}
Know your tools!




            X
function setupPage() {
  $('userName').update(
     readUserName();
  );
}

function readUserName() {
  //read user's name from cookie
}
Know your tools!
var Application = (function() {

  //private
  var readUserName = function() {
     //read user's name from cookie
  };

  return {

      //public
      setupPage: function() {
        $('userName').update(
           readUserName();
        );
      }

  }

})();
Know your tools!


var timeout = window.setTimeout(
   "element.update(" + someContent
     + ");",
   1000
);
Know your tools!




            X
var timeout = window.setTimeout(
   "element.update(" + someContent
     + ");",
   1000
);
Know your tools!

Protoype.js
element.update.bind(element).curry(
  someContent
).delay(1)
Know your tools!


var loginField =
  document.getElementById('#user_login');
alert(loginField.value);
Know your tools!




              X
var loginField =
  document.getElementById('#user_login');
alert(loginField.value);
Know your tools!

Protoype.js
alert($F('user_login'));

jQuery
alert($('#user_login').val());
Know your tools!


var loginField =
  document.getElementById('#user_login');
loginField.style.display = 'none';
Know your tools!




              X
var loginField =
  document.getElementById('#user_login');
loginField.style.display = 'none';
Know your tools!

Protoype.js
$('user_login').hide();

jQuery
$('#user_login').hide();
Know your tools!
var loginField =
  document.getElementById('user_login');
function loginChanged() {
  alert(loginField.value);
}
if (loginField.addEventListener) {
  loginField.addEventListener(
    'change', loginChanged, false);
} else if (obj.attachEvent) {
  obj.attachEvent('onchange', loginChanged);
}
Know your tools!




               X
var loginField =
  document.getElementById('user_login');
function loginChanged() {
  alert(loginField.value);
}
if (loginField.addEventListener) {
  loginField.addEventListener(
    'change', loginChanged, false);
} else if (obj.attachEvent) {
  obj.attachEvent('onchange', loginChanged);
}
Know your tools!
Protoype.js
$('user_login').observe(
  'change', function(event) {
    alert($F('user_login'));
});

jQuery
$('#user_login').change(function() {
  alert(this.val());
});
Write valid
JavaScript!
Write valid JavaScript!

someValue    = 0;
anotherValue = 1;

function fun(param) {
  alert(param)
}
Write valid JavaScript!




            X
someValue    = 0;
anotherValue = 1;

function fun(param) {
  alert(param)
}
Write valid JavaScript!

var someValue    = 0;
var anotherValue = 1;

function fun(param) {
  alert(param);
}
Write valid JavaScript!


someValue    = 0;
anotherValue = 1;

function fun(param) {
  alert(param)
}
Write valid JavaScript!


someValue    = 0;
anotherValue = 1;

function fun(param) {
  alert(param)
}
Write valid JavaScript!


someValue    = 0;       Missing semicolon.
anotherValue = 1;
                        Implied globals:
function fun(param) {   someValue, anotherValue
  alert(param)
}
JavaScript and
    Rails
JavaScript and Rails


•RESTful actions (delete, put, post)
•AJAX
•Effects
•etc.
the Demo App
the Demo App




 POST/replace
the Demo App




                POST/replace
Code is at http://github.com/marcoow/js-and-rails
3 possible
Solutions
the classic
 Solution
the classic Solution

•Helpers (remote_form_for,   link_to_remote
 etc.)
•RJS
•onclick=“...
•href=“javascript:...
the classic Solution

index.html.erb
<div id="someElement">
  some text that's replaced later
</div>
<%= link_to_remote 'Replace', :url =>
       classic_solution_replace_path,
       :method => :post %>
the classic Solution
class ClassicSolutionController <
ApplicationController

  def index
  end

  def replace
  end

end
the classic Solution


replace.rjs
page.replace_html 'someElement',
  :partial => 'new_content'
the classic Solution

_new_content.html.erb
<b>Fresh new content rendered at <%=
  Time.now %></b>
<%= link_to_remote 'Replace again',
    :url => classic_solution_replace_path,
    :method => :post %>
the classic Solution
•strong coupling
•hard to maintain
•no/ little code reuse
•bloated HTML
•code that actually belongs together is
 distributed over several places
•easy to write in the first place
Full Separation
Full Separation
•define JavaScript controls that encapsulate
 all frontend logic
•mark elements with class, rel or HTML5‘s
 data-* attributes
•full separation of HTML and JavaScript
•Initialization of controls on dom:loaded
 event
Full Separation
•define JavaScript controls that encapsulate
 all frontend logic
•mark elements with class, rel or HTML5‘s
 data-* attributes
•full separation of HTML and JavaScript
•Initialization of controls on dom:loaded
 event
Full Separation
replacer.js
var Replacer = Class.create({

  initialize: function(container, target) {
     this.container = $(container);
     this.target    = $(target);
     this.container.observe('click', this.onClick.bindAsEventListener(this));
  },

  onClick: function(event) {
    event.stop();
    new Ajax.Updater(
       this.target,
       this.container.href, {
         method:      'post',
         evalScripts: true
       }
    );
  }

});
Full Separation
application.js
var Application = (function() {

  var initializeReplacers = function() {
     $$('a[data-replaces]').each(function(replacingLink) {
       if (!replacingLink._initializedReplacer) {
         new Replacer(replacingLink, replacingLink.readAttribute('data-replaces'));
         replacingLink._initializedReplacer = true;
       }
     });
  };

  return {

      setupOnLoad: function() {
         initializeReplacers();
      },

      setupOnPageUpdate: function() {
        initializeReplacers();
      }

  }

})();
Full Separation

application.js
document.observe('dom:loaded', function() {
  Application.setupOnLoad();
  Ajax.Responders.register({
    onComplete: Application.setupOnPageUpdate
  });
});
Full Separation

application.js
document.observe('dom:loaded', function() {
  Application.setupOnLoad();
  Ajax.Responders.register({
    onComplete: Application.setupOnPageUpdate
  });
});


Replacer controls are initialized on page load
and after every AJAX request
Full Separation

index.html.erb
<div id="someElement">
  some text that's replaced later
</div>
<%= link_to 'Replace', full_separation_replace_path,
       :'data-replaces' => 'someElement' %>
Full Separation
class FullSeparationController <
ApplicationController

  def index
  end

  def replace
    respond_to do |format|
      format.js { render :partial => 'new_content' }
    end
  end

end
Full Separation

_new_content.html.erb
<b>Fresh new content rendered at
  <%= Time.now %></b>
<%= link_to 'Replace again',
    full_separation_replace_path,
    :'data-replaces' => 'someElement' %>
Full Separation

•clean, semantic HTML
•full separation of concerns
•clean HTML/CSS/JS is crucial
•Behaviour is (kind of) implicit
•discipline required
explicit
Controls
explicit Controls


•like Full Separation
•but controls are initialized in the templates
•more explicit/ obvious what‘s going on
explicit Controls

index.html.erb
<div id="someElement">
  some text that's replaced later
</div>
<%= link_to 'Replace', controls_replace_path,
       :id => 'replacerLink' %>
<script type="text/javascript" charset="utf-8">
  document.observe('dom:loaded', function() {
    var replacer = new Replacer('replacerLink', 'someElement');
  });
</script>
explicit Controls
class ControlsController < ApplicationController

  def index
  end

  def replace
    respond_to do |format|
      format.js { render :partial => 'new_content' }
    end
  end

end
explicit Controls
_new_content.html.erb
<b>Fresh new content rendered at
  <%= Time.now %></b>
<%= link_to 'Replace again', controls_replace_path,
       :id => 'secondReplacerLink' %>
<script type="text/javascript" charset="utf-8">
  var newReplacer = new Replacer(
     'secondReplacerLink', 'someElement'
  );
</script>
explicit Controls
_new_content.html.erb
<b>Fresh new content rendered at
  <%= Time.now %></b>
<%= link_to 'Replace again', controls_replace_path,
       :id => 'secondReplacerLink' %>
<script type="text/javascript" charset="utf-8">
  var newReplacer = new Replacer(
     'secondReplacerLink', 'someElement'
  );
</script>

No initialization on dom:loaded here as this is
the result of an AJAX request (dom:loaded not
fired)
explicit Controls

•HTML is (mostly) clean and semantic
•Behaviour is explicit in the templates
•easier to grasp what‘s going on than with
 Full Separation
•though not as nice as full separation
Either go with
Full Separation
  or explicit
   Controls!
Avoid the
classic Solution
 when you can!
Resources
Resources

•http://ejohn.org/apps/learn/
•http://www.jslint.com/
•http://api.prototypejs.org/
•http://docs.jquery.com
•http://github.com/marcoow/js-and-rails
•http://javascriptrocks.com
Q&A

Contenu connexe

Tendances

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Java script object model
Java script object modelJava script object model
Java script object model
James Hsieh
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 
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
Eldar Djafarov
 

Tendances (20)

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Java script object model
Java script object modelJava script object model
Java script object model
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications Testing JavaScript with Jasmine in Rails Applications
Testing JavaScript with Jasmine in Rails Applications
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
 
Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communication
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Getting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe TestingGetting to Grips with SilverStripe Testing
Getting to Grips with SilverStripe Testing
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
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
 
정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Ember and containers
Ember and containersEmber and containers
Ember and containers
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 

Similaire à Rails is not just Ruby

Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
adamlogic
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 

Similaire à Rails is not just Ruby (20)

jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
React 101
React 101React 101
React 101
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
jQuery
jQueryjQuery
jQuery
 

Dernier

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
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
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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...
 
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...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Rails is not just Ruby