SlideShare a Scribd company logo
codecentric d.o.o
Jovan Vidić, IT Consultant @ codecentric
Refactoring Java Script Applications
Motivation
Should We Refactor JavaScript?
Refactoring Sample Application
Beyond Refactoring
Agenda
~ 6 years of development
Java + DWR
732 JavaScript files
~ 20 000 lines of javascript code
Motivation - Legacy project
What was wrong?
- JavaScript in HTML
- Global functions
- Inline styles
- No coding style guidelines
- No tests
MOTIVATION - Legacy project

Recommended for you

Modern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on RailsModern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on Rails

In a world of emerging JavaScript, is Rails getting left behind? Are server-side MVC applications out and static single page applications in? In this talk I’ll describe how we’ve used webpack(er) and Vue to revitalize our JavaScript approach within an aging Rails application. You can have it both ways.

javascriptvuerails
A tour of React Native
A tour of React NativeA tour of React Native
A tour of React Native

React Native is an open source framework by Facebook that enables software engineers to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. I'll talk about what React Native actually is (and what it isn't), how it works under the hood, and why it was designed like that.

react-nativejavascript
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...

Watch full webinar recording here: https://youtu.be/HFxL_658Gcg Listen to Fortune-100 Test Automation Expert Joe Colantonio present this hands-on webinar, and learn how by implementing large-scale automated visual testing, he was able to ​dramatically increase coverage, reduce maintenance, and substantially boost test robustness, efficiency, and ROI. In order to help you release faster and better, while avoiding functional and visual regressions, Joe dives deep into the following real-life use cases: * Automating cross-browser UI validation * Adding full UI regression coverage to existing automated tests * Handling dynamic content in visual tests In addition, Joe covers the basics of automated visual testing, including a live demo of adding visual regression and cross-browser layout testing to existing automated tests using Applitools Eyes.

automated visual testingsoftware qualitysoftware testing
What was OK?
- OOP
- Throwing own errors
- Wrapping third party libraries
- Prototype.js
MOTIVATION - Legacy project
Should We Refactor JavaScript ?
“It is not necessary to change.
Survival is not mandatory”
W. Edwards Deming
W E Deming
What is Refactoring?

Recommended for you

How to React Native
How to React NativeHow to React Native
How to React Native

This document provides an overview of how to build applications with React Native. It discusses React Native's core components like React, ReactDOM and React Native. It also covers topics like JavaScript implementation, building components, styles, platform specific code, animations, navigation libraries and working with data using Redux.

react nativereactredux-saga
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native

React Native allows developers to use React and JavaScript to build mobile apps for Android and iOS. It uses the same fundamental UI building blocks as regular React, such as JSX, components, and unidirectional data flow. However, instead of rendering to the DOM, React Native renders native mobile UI components. This allows apps written in React Native to look and feel like they were built for each native platform, while sharing common JavaScript code between platforms. React Native is still young but is gaining popularity due to its promise of allowing web developers to build truly native mobile apps while reusing their existing skills.

reactcross platformmobile application development
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action

1) Apache Cordova allows developers to use web technologies like HTML, CSS, and JavaScript to build mobile apps that can access native device features and be deployed to app stores. 2) Cordova uses a command line interface for creating projects, adding platforms, and building apps. It also provides APIs for accessing device features through plugins. 3) jQuery Mobile is a popular framework for building the user interface of Cordova apps, though other frameworks can also be used. Special considerations are needed for each mobile platform.

apachecordovaios
What is Refactoring?
a change made to the internal structure of software
to make it easier to understand and cheaper to modify
without changing its observable behavior
M. Fowler
This is not refactoring
agile manifesto 8th principle
Agile processes promote sustainable development.
The sponsors, developers, and users should be able
to maintain a constant pace indefinitely.
Refactoring Sample Application – v1 – index.html
</head>!
<body>!
<ul class="nav nav-pills">!
<li class="active"><a href="../../v1/client/index.html">V1</a></
li>!
<li><a href="../../v2/client/index.html">V2</a></li>!
<li><a href="../../v3/client/index.html">V3</a></li>!
<li><a href="../../v4/client/index.html">V4</a></li>!
<li><a href="../../v5/client/index.html">V5</a></li>!
</ul>!
<div class="page-header">!
<h1>Coding Serbia <small> Refactoring JavaScript Applications -
V1</small></h1>!
</div>!
!
<button class="btn btn-primary btn-lg" data-toggle="modal"
onclick="createSpeaker()">!
Add Speaker!
</button>!

Recommended for you

Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...

2011-10-31 | 02:15 PM - 03:00 PM There are many tools out there to help developers working with the Spring framework and its manifold extensions. But it's not always easy to choose the right tool for the job. This talk guides you through the tooling landscape for Spring and illustrates when to use Spring Roo, WaveMaker or the SpringSource Tool Suite. Demos and examples give the audience first-hand insights and useful hints how to use and combine those tools effectively.

jaxjax londonjava
[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration

The document discusses JavaFX and its integration with web technologies. It provides an overview of JavaFX's built-in web browser capabilities through the WebEngine and WebView APIs. These allow JavaFX applications to load web content, access DOM elements, and evaluate JavaScript. The document also demonstrates how to integrate Java code with web applications through JavaScript bridges and modifying the DOM from Java.

javafxjavajavaone
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon RitterJava Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter

2011-11-02 | 01:30 PM - 02:15 PM | Victoria With the recent release of Java SE 7 the Java platform is back on the move, addressing the needs of developers as platforms and applications change. This session will briefly recap recent developments in Java SE 7 and the Java Community Process before moving onto the current ideas for features in Java SE 8. Discussions are underway within Oracle about the main themes for Java SE 9 and beyond. We'll conclude with an open discussion around what features the audience would like to see included in future releases of the Java platform. Key points from this will be passed back to Java SE product management in Oracle.

jaxjax londonjava
<script src="js/jquery.min.js"></script>!
<script src="js/bootstrap.min.js"></script>!
<script src="js/speakers.js"></script>!
!
<script type="text/javascript">!
load();!
</script>!
</body>!
Refactoring Sample Application – v1 – index.html
Refactoring Sample Application – v1 – speakers.js
function add() {!
var speakerId = $('#speakerId').val();!
!
$.ajax({!
type: speakerId == '' ? "POST" : "PUT",!
url: speakerId == '' ? "http://localhost:4730/speakers" : "http:/!
data: JSON.stringify({id: speakerId, firstName: $('#firstName').v!
contentType: "application/json; charset=utf-8",!
dataType: "json",!
success: function(data){ $('#speakerId').val(''); $('#firstName’)!
failure: function(errMsg) {alert(errMsg);}!
!
function load() {!
$.getJSON( "http://localhost:4730/speakers", function( data ) {!
var newRows = "";!
$.each(data, function(i,item) {!
var sessionTime = new Date(Date.parse(item.sessionTime));!
!
newRows += "<tr><td>" + sessionTime.toLocaleString() +"</td><!
});!
$(".table-striped tbody").html("");!
$(".table-striped tbody").append(newRows);!
});!
};!
Refactoring Sample Application – v1
It is a complete mess!
How should I start?
Refactoring Sample Application – v1 – selenium

Recommended for you

Agile toolkit present 2012
Agile toolkit present 2012Agile toolkit present 2012
Agile toolkit present 2012

Agile Toolkit is a PHP framework for developing Powerful Web Applications. Inspired by Desktop Toolkits (QT, Cocoa, .NET) it provides clever web application framework for developers with any skill level.

phpphp frameworkweb development
Angularjs Tutorial for Beginners
Angularjs Tutorial for BeginnersAngularjs Tutorial for Beginners
Angularjs Tutorial for Beginners

TIB Academy is one of the best AngularJS Training Institute in Bangalore. We Offers Hands-On Training with Live project.

angularjs trainingangularjsbest angularjs training in bangalore
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.ioContinuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io

Unit testing is mostly a solved problem, but how do you write tests for the visual side of your app—the part that your users actually see and interact with? How do you stop visual bugs from reaching your users? We will dive deep into visual regression testing, a fast-growing technique for testing apps pixel-by-pixel. We will integrate perceptual diffs in Rails feature specs, and learn how to visually test even complex UI states. We will show tools and techniques for continuous visual integration on every commit, and learn how to introduce team visual reviews right alongside code reviews.

visual testingpercyvisual regression testing
Refactoring Sample Application – v1
What about JSLint/JSHIT?
It will scream at you!
Refactoring Sample Application – v2
Invert dependencies
Refactoring Sample Application – v2 - REQUIREJS
requirejs.config({!
paths: {!
"jquery": "lib/jquery.min",!
"bootstrap": "lib/bootstrap.min"!
},!
shim: {!
"bootstrap": {!
deps: ["jquery"]!
}!
}!
});!
!
require(["app/speakers","bootstrap"], function (speakers) {!
!
$("#btnSaveSpeaker").click(function() {!
speakers.save();!
});!
!
speakers.loadAll();!
});!
<script data-main="scripts/main" src="scripts/lib/require.js"></script>!

Recommended for you

Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011

The document discusses creating a strong documentation culture. It notes that everyone reads documentation for various reasons such as first contact, education, support, troubleshooting, and reference. Great documentation has different types of content including tutorials for new users, topic guides for conceptual understanding, reference materials, and troubleshooting guides. Documentation should be written by developers and be "fractal" in its level of detail. While tools are not most important, good documentation tools like Sphinx and Read the Docs can help. The overall aim is to establish a culture where developers recognize the importance of documentation.

documentationdjangocodeconf
Creating books app with react native
Creating books app with react nativeCreating books app with react native
Creating books app with react native

Ali Hussein Al-Sa'o is a senior front end developer with 10 years of experience in web development. The session will cover an introduction to React and React Native, including what they are, their key characteristics, and an installation guide. It will also discuss debugging in React Native and provide an overview of coding and additional resources. React Native allows building mobile apps using only JavaScript and aims to provide a faster development cycle than alternatives like Cordova through features like live reloading and over-the-air updates.

react-nativemobile-developmentreact
BPM-2 Introduction to Advanced Workflows
BPM-2 Introduction to Advanced WorkflowsBPM-2 Introduction to Advanced Workflows
BPM-2 Introduction to Advanced Workflows

This session will introduce the audience to the workflow capabilities available in Alfresco. We will discuss the workflow UI in Share and the configuration options available. A working example will also show how custom Activiti workflows can be implemented, deployed, configured and monitored.

workflowalfresco sharedevcon 2011
Refactoring Sample Application – V2 – SPEAKERS.JS & THEME.jS
define(["jquery","app/theme"], function ($, theme) {!
"use strict";!
!
var SpeakerControler = {!
loadAll : function () {!
$.getJSON("http://localhost:4730/speakers", function (data) {!
var speakersTable = $("." + theme.SPEAKERS_TABLE +" tbody")
define([], function () {!
"use strict";!
!
return {!
DELETE_BUTTON : "btn btn-danger glyphicon glyphicon-remove",!
EDIT_BUTTON : "btn btn-default glyphicon glyphicon-pencil",!
SPEAKERS_TABLE : "table-striped"!
};!
});!
Refactoring Sample Application – SPEAKERS.JS
define(["jquery","app/theme"], function ($, theme) {!
"use strict";!
!
var SpeakerControler = {!
loadAll : function () {!
cell.append($("<button class='"+theme.DELETE_BUTTON+"'></button>”)!
SpeakerControler.remove(item.id);!
}));
remove : function(id) {!
$.ajax({!
type: "DELETE",!
url: "http://localhost:4730/speaker/" + id,!
success: function() {!
SpeakerControler.loadAll();!
}!
});!
}!
return SpeakerControler;!
});
My code is isolated now
Can I write unit tests?
Refactoring JavaScript Applications

Recommended for you

React native
React nativeReact native
React native

React Native is a framework for building native mobile apps using React. It was created by Facebook in 2013 and allows using React to build mobile apps that look and feel native on both iOS and Android. Some key advantages of React Native include being friendly for web developers, supporting native UI instead of web views, enabling live reloading instead of compiling and waiting, and using declarative UI rather than imperative UI. Components, props, state, and JSX are some important concepts in React Native. Getting started involves installing Node, Watchman, and the React Native CLI, then creating a project and running it on iOS or Android. Common React Native components include Text, Image, View, TouchableOpacity, and more.

native appjsxreact
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...

JavaScript MVC Frameworks are all the rage these days. They’ve taken the web development world by storm. This session explores the various features of the three hottest JavaScript MVC frameworks: AngularJS, Ember.js and React.js. It also compares client-side templating vs. server-side templating and how well each framework supports Isomorphic JavaScript (code that can run both client-side and server-side). Finally, it ranks each framework on 10 different criteria using Yevgeniy Brikman’s framework scorecard. Video on InfoQ: https://www.infoq.com/presentations/comparing-angular-ember-react

ember.jsangularjsreact.js
Redefining Projects For an Age of Complexity
Redefining Projects For an Age of ComplexityRedefining Projects For an Age of Complexity
Redefining Projects For an Age of Complexity

The document discusses complexity and project management. It introduces the Cynefin framework, which categorizes problem domains as simple, complicated, complex, or chaotic based on the relationship between cause and effect. Within each domain lie different leadership approaches and risks. The complex domain involves emergent patterns, uncertainty, and a leadership approach of probing and responding. Overall the document presents frameworks for understanding complexity and navigating uncertain problem domains.

agilecomplexityagile software development
Refactoring Sample Application – v3
Manage dependencies
Refactoring Sample Application – v3 – bower.json
{!
"name": "javascript-refactoring",!
"version": "1.0",!
"authors": [!
"Jovan Vidic
<jovan.vidic@codecentric.de>"!
],!
"private": true,!
"ignore": [!
"node_modules",!
"bower_components",!
"test",!
"tests"!
],!
"dependencies": {!
"jquery": "1.11.1",!
"bootstrap" : "3.2.0",!
"requirejs" : "2.1.15"!
},!
!
"devDependencies": {!
!
}!
}!
Refactoring Sample Application – v4
Improve design
Introduce model objects & unit tests
Refactoring Sample Application – v4 – MODEL.JS
function Speaker(id, firstName, lastName, topic, sessionTime, track) {!
this.id = id;!
this.firstName = firstName;!
this.lastName = lastName;!
this.topic = topic;!
this.sessionTime = sessionTime;!
this.track = track;!
!
this.hasId = function () {!
return (this.id !== undefined) && (this.id !== null) !
&& (this.id !== "");!
};!
!
this.getFullName = function () {!
return this.firstName + " " + this.lastName;!
};!
}!
!
return {!
"Agenda" : {!
"Speaker" : Speaker!
}!
};!

Recommended for you

How To Start Agile Competence Center
How To Start Agile Competence CenterHow To Start Agile Competence Center
How To Start Agile Competence Center

The document discusses establishing an Integration Competence Center to help organizations adopt agile practices and lean integration. It provides lessons from the auto industry on lean production and continuous improvement. It also outlines models for competence centers and recommends establishing clear goals and organizational learning practices to help integration. Leaders are advised to think strategically, gain credibility through delivery, and grow the center incrementally through the plan-do-study-act cycle.

agileleanlean integration
LA COLUMNA VERTEBRAL
LA COLUMNA VERTEBRALLA COLUMNA VERTEBRAL
LA COLUMNA VERTEBRAL

La columna vertebral está formada por 26 huesos llamados vértebras que se dividen en regiones cervical, dorsal, lumbar, sacra y cóxigea. Sus principales funciones son dar soporte al cuerpo, proteger la médula espinal y mantener el centro de gravedad. Los problemas más comunes son infecciones, traumatismos, tumores, cifosis, hiperlordosis y escoliosis. La cifosis es una curvatura excesiva de la columna de más de 45 grados que limita el movimiento, mientras que la escoliosis es una curvatura lateral anormal

5 Games for Effective Agile Coaching
5 Games for Effective Agile Coaching5 Games for Effective Agile Coaching
5 Games for Effective Agile Coaching

If you work in Scrum environment or you’re just a team member who is trying to guide a conversation – then these interactive facilitation techniques are for you. In this session focus will be on games which you could use in virtual environment.

agileagile gamesscrum
Refactoring Sample Application – v4 – Speakers.JS
define(["jquery", "app/model", "app/theme"], function ($, model, theme) {!
"use strict";!
var SpeakerControler = {!
editSpeaker : function(id) {!
$.getJSON( "http://localhost:4730/speaker/" + id, !
function(speakerData) {!
if(speakerData) {!
var speaker = convertToModel(speakerData);!
showEditSpeakerPopup(speaker);!
}!
});!
}!
function showEditSpeakerPopup(speaker) {!
$('#myModalLabel').html('Edit speaker <strong>' !
+ speaker.getFullName() + "</strong>");!
}!
function convertToModel(speakerData) {!
return new model.Agenda.Speaker(speakerData.id,
speakerData.firstName, speakerData.lastName, speakerData.topic,
speakerData.sessionTime, speakerData.track);!
}
Refactoring Sample Application – v4 – jasmine
describe("Test model objects", function() {!
"use strict";!
!
var Model;!
!
beforeEach(function(done) {!
require(["app/model"], function (model) {!
Model = model;!
done();!
});!
});
it("should return Jovan Vidic when firstName is Jovan and lastName is
Vidic", function() {!
!
var speaker = new Model.Agenda.Speaker(1, "Jovan", "Vidic");!
!
expect(speaker.getFullName()).toBe("Jovan Vidic");!
});!
Refactoring Sample Application – v4
That's all cool but my code still stinks?!
Trust me I've been there

Recommended for you

La Higiene Postural
La Higiene PosturalLa Higiene Postural
La Higiene Postural

La columna vertebral tiene curvaturas que permiten distribuir la presión del cuerpo de manera homogénea. Una postura correcta, con la cabeza erguida y las curvaturas normales, es importante para mantener una espalda sana. Al levantar objetos pesados se debe usar las piernas flexionando las rodillas y manteniendo la espalda recta para evitar lesiones.

Higiene Postural 2º ESO
Higiene Postural 2º ESOHigiene Postural 2º ESO
Higiene Postural 2º ESO

Este documento trata sobre la higiene postural y ofrece consejos sobre cómo mantener una postura correcta en diversas actividades diarias como estar de pie, sentado, levantando objetos, transportando cargas e inclinándose. Explica que una buena postura ayuda a prevenir lesiones y dolores musculares a largo plazo.

Higiene postural[1]
Higiene postural[1]Higiene postural[1]
Higiene postural[1]

Este documento describe la higiene postural y su importancia para prevenir problemas de espalda. La higiene postural se refiere a mantener una postura correcta del cuerpo para reducir la tensión en la espalda. Una mala postura puede causar dolores de espalda, cuello y otros problemas. El documento también explica la anatomía de la columna vertebral y factores que afectan la postura como el trabajo y calzado inadecuado.

Refactoring Sample Application – v5
Improve design
&
automate
Refactoring Sample Application – v5 – SPEAKERS AJAX CLIENT
define(["jquery", "app/model"], function ($, model) {!
"use strict";!
!
var baseURL = requirejs.s.contexts._.config.cs["api-url"],!
speakersURL = baseURL + "speakers/",!
speakerURL = baseURL + "speaker/";!
!
function convertToModel(speakerData) {!
return new model.Agenda.Speaker(speakerData.id, speakerData.firstNa
}!
return {!
loadAllSpeakers : function (callbackHandle) {!
$.getJSON(speakersURL, function (speakersData) {!
var speakers = [];!
$.each(speakersData, function (index, speakerData) {!
var speaker = convertToModel(speakerData);!
speakers.push(speaker);!
});!
callbackHandle.success(speakers);!
});!
},
Refactoring Sample Application – v5 – Backend FACADE
define(["app/client/speakers_ajax_client"], function (speakersClient) {!
"use strict";!
!
return {!
loadAllSpeakers : function (callbackHandle) {!
speakersClient.loadAllSpeakers(callbackHandle);!
},!
!
saveSpeaker : function (speaker, callbackHandle) {!
speakersClient.saveSpeaker(speaker, callbackHandle);!
}!
Refactoring Sample Application – v5 - TesTS
define(["squire"], function (Squire) {!
"use strict";!
!
var injector = new Squire(),!
client = jasmine.createSpyObj("client", ["loadAllSpeakers",
"saveSpeaker", "removeSpeaker"]),!
callbackHandle = jasmine.createSpy("callback"),!
builder = injector.mock("app/client/speakers_ajax_client”, client);
!
describe("Test backend facade", function() {!
!
var backend;!
!
beforeEach(function(done) {!
builder.require(["app/backend_facade"], function(backendFacade)
backend = backendFacade;!
done();!
});!
});!
it("should loadAllSpeakers", function() {!
backend.loadAllSpeakers(callbackHandle);!
expect(client.loadAllSpeakers)!
.toHaveBeenCalledWith(callbackHandle);!
});!
!
!

Recommended for you

Capacitacion higiene postural
Capacitacion higiene posturalCapacitacion higiene postural
Capacitacion higiene postural

El documento proporciona recomendaciones para prevenir lesiones en la espalda mediante el mantenimiento de una buena postura y técnicas de levantamiento seguras, ejercicio físico regular, alimentación balanceada y evitar sobreesfuerzos.

Enfermedades ocupacionales
Enfermedades ocupacionalesEnfermedades ocupacionales
Enfermedades ocupacionales

El documento habla sobre lesiones osteomusculares de origen ocupacional. Explica que factores como posturas mantenidas, movimientos repetitivos, fuerza excesiva y cargas estáticas pueden causar lesiones como tendinitis, bursitis y dolor lumbar. También menciona que estas lesiones tienen alta incidencia, causan ausentismo laboral y generan costos para la salud y la industria.

Higiene postural
Higiene posturalHigiene postural
Higiene postural

El documento habla sobre la higiene postural y las causas de la mala postura. Identifica factores como problemas visuales, emocionales, exceso de peso, problemas en los pies o zapatos inadecuados, nutrición inapropiada, músculos débiles, sedentarismo y soporte inadecuado al dormir como causas comunes de mala postura. También explica que muchos problemas de postura se pueden corregir y los beneficios de tener una buena postura, como mejor salud, fuerza, confianza y reducción de lesiones.

Refactoring Sample Application – v5 - MVP
http://warren.chinalle.com/2010/12/18/model-view-presenter/
Refactoring Sample Application – v5 – speakers PRESENTER
define(["app/backend_facade", "app/speakers/speakers_view", !
"app/events"], function (backend, SpeakersView, events) {!
!
"use strict";!
!
var EventManager = events.EventManager,!
Actions = events.Actions;!
!
function SpeakerPresenter() { !
var view = new SpeakersView(),!
self;!
!
return {!
init : function () {!
self = this;!
EventManager.register(Actions.LOAD_ALL_SPEAKERS, this.loadAll);!
},!
loadAll : function () {!
backend.loadAllSpeakers({!
"success" : function (speakers) {!
view.showAll(speakers);!
}!
});!
},!
Refactoring Sample Application – v5 – Speakers view
define(["app/events", "app/components", "app/speakers/speakers_popup"], !
"use strict”;!
var EventManager = events.EventManager;!
!
function SpeakersView() {!
var speakersTable = new components.SpeakersTable(),!
createButton = new components.Button("btnAddSpeaker"),!
popup = new SpeakersPopup();!
!
function showCreateSpeakerDialog() {!
EventManager.fire(events.Actions.SHOW_CREATE_SPEAKER);!
}!
function init() {!
createButton.addClickListener(showCreateSpeakerDialog);!
}!
init();!
return {!
showAll : function (speakers) {!
var i, len;!
speakersTable.clear();!
for (i = 0, len = speakers.length; i < len; i += 1) {!
speakersTable.addSpeaker(speakers[i]);!
}!
}!
Refactoring Sample Application – v5 – SPEAKERS POPUP
define(["app/model", "app/events", "app/components"], function (model, even
!
function SpeakersPopup() {!
var speaker,!
popup = new components.Popup("myModal"),!
firstNameInput = new TextField("firstName"),!
!
function saveSpeaker() {!
speaker.firstName = firstNameInput.val();!
speaker.lastName = lastNameInput.val();!
speaker.topic = topicInput.val();!
!
if (speaker.hasId()) {!
EventManager.fire(events.Actions.EDIT_SPEAKER, speaker);!
} else {!
EventManager.fire(events.Actions.SAVE_SPEAKER, speaker);!
}!
}!
return {!
openAndSet : function (speakerToUpdate) {!
speaker = speakerToUpdate;!
firstNameInput.val(speaker.firstName);!
lastNameInput.val(speaker.lastName);!
!

Recommended for you

Higiene postural y pausas activas
Higiene postural y pausas activasHigiene postural y pausas activas
Higiene postural y pausas activas

Este documento habla sobre la importancia de la ergonomía y la higiene postural para prevenir lesiones en la columna vertebral. Recomienda educar sobre la mecánica corporal correcta al realizar tareas y tomar pausas activas cada hora o dos para estirar, fortalecer y movilizar los músculos. Además, sugiere no adoptar posturas por mucho tiempo, controlar el peso y realizar ejercicio regularmente para cuidar la salud de la espalda.

Principales enfermedades causadas por una mala postura corporal
Principales enfermedades causadas por una mala postura corporalPrincipales enfermedades causadas por una mala postura corporal
Principales enfermedades causadas por una mala postura corporal

Este documento describe las principales enfermedades causadas por una mala postura corporal, incluyendo tortícolis, lumbalgia, lordosis, escoliosis y miopatías. Tortícolis es un torcimiento del cuello donde la cabeza apunta a un lado mientras la barbilla apunta al otro. Lumbalgia es una alteración de un nervio por la deformación y compresión de la columna vertebral en la región lumbar. Miopatías son causadas por la posición de los pies al sentarse, lo que puede producir contracturas musculares y mala circulación

posturacotidianacorporal
Ergonomía higiene postural
Ergonomía  higiene posturalErgonomía  higiene postural
Ergonomía higiene postural

El documento trata sobre la ergonomía y la higiene postural. Explica la importancia de mantener una postura correcta al sentarse, levantar pesos y realizar actividades deportivas para prevenir dolores de espalda. Detalla recomendaciones sobre posturas adecuadas y técnicas de levantamiento para reducir la sobrecarga de la columna vertebral. También analiza los beneficios y riesgos de diferentes deportes como la natación y el baloncesto para la espalda.

espalda
Refactoring Sample Application – v5 – components
http://warren.chinalle.com/2010/12/18/model-view-presenter/
define(["jquery", "app/events", "app/theme"], function ($, events, theme)
!
function TextField(id) {!
var textField = $("#" + id);!
return {!
val : function (value) {!
if (value !== undefined) {!
textField.val(value);!
} else {!
return textField.val();!
}!
}!
};!
}!
!
function SimpleButton(id) {!
var button = $("#" + id);!
return {!
addClickListener : function (listener) {!
button.click(listener);!
}!
};!
}!
!
For the win
Refactoring Sample Application – v5 - GRUNT
grunt.initConfig({!
!
jslint: {!
src: [!
"scripts/**/*.js"!
],!
!
},!
!
karma: {!
unit: {!
configFile: "karma.conf.js"!
}!
},!
!
copy: {!
main: {!
files: [!
{expand: true, src: ["lib/bootstrap/dist/css/**"], dest: "dist/"},!
{expand: true, src: ["lib/bootstrap/dist/fonts/**"], dest: "dist/"}
{expand: true, src: ["lib/requirejs/require.js"], dest: "dist/"}!
]!
}!
}!
Refactoring Sample Application – v5 - GRUNT
requirejs: {!
compile: {!
options: {!
baseUrl: "scripts/",!
name: "main",!
out: "dist/app-built.js”,!
paths: {!
app: "app/",!
"jquery": "../lib/jquery/dist/jquery.min",!
"bootstrap": "../lib/bootstrap/dist/js/bootstrap"!
}!
}!
}!
},!
processhtml: {!
options: {!
data: { !
}!
},!
dist: {!
files: {!
"dist/index.html": ["index.html"]!
}!
}!

Recommended for you

Taller de higiene postural
Taller de higiene posturalTaller de higiene postural
Taller de higiene postural

El documento presenta imágenes extraídas de un trabajo sobre la higiene postural del escolar realizado por Simón Pedro Simón Ruano. Las fotografías pertenecen a alumnos y alumnas de un colegio en Alcantarilla y están autorizadas. Muestra imágenes de posturas normales y anormales como la escoliosis, hipercifosis, hiperlordosis e inversión, así como ilustraciones anatómicas de músculos. El documento concluye que los patrones posturales se aprenden desde la infancia y depende de las

higiene postural
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...

This document provides an overview of designing complex applications using HTML5 and KnockoutJS. It discusses HTML5 and why it is useful, introduces JavaScript and frameworks like KnockoutJS and SammyJS that help manage complexity. It also summarizes several JavaScript libraries and patterns including the module pattern, revealing module pattern, and MV* patterns. Specific libraries and frameworks discussed include RequireJS, AmplifyJS, UnderscoreJS, and LINQ.js. The document concludes with a brief mention of server-side tools like ScriptSharp.

sammyjshtml5javascript
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)

Node.js is a platform built on Chrome V8 javascript runtime engine for building fast and scalable, non-blocking, real-time and network applications. In this session Ran will introduce node.js and how to develop large code bases using it. He'll cover the following aspects: • What is node.js? • Apache vs. Nginx performance (One thread per connection vs. event loop) and what it has to do with node.js. • Why node was written in Javascript? • Main tools and frameworks (Express, socket.io, mongoose etc.) • TDD/BDD with node.js using mocha and Chai. Ran Mizrahi, Founder of CoCycles, Passionate entrepreneur and software engineer who loves to continuously innovate and deliver meaningful products while having true fun with the right team.

javascripttddnode.js
BEYOND REFACTORING
Coffeescript
define [], () ->!
!
class Speaker!
constructor: (@id, @firstName, @lastName, @topic, @sessionTime, @track)
->!
!
hasId: ->!
@id?.length != 0!
!
fullName: ->!
@firstName + " " + @lastName!
!
return {"Agenda": {"Speaker" : Speaker}} !
Literature
Refactoring JavaScript Applications

Recommended for you

Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)

This document provides an introduction to Node.js, including what it is, how it works, and some common frameworks and tools used with Node.js. Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that uses an event-driven, non-blocking I/O model to handle requests. It allows for easy development of scalable network applications. The document discusses Node.js' event loop architecture, non-blocking I/O, and provides examples of using Express, Socket.IO, Mongoose and testing with Mocha/Chai.

Avatar 2.0
Avatar 2.0Avatar 2.0
Avatar 2.0

The document is a presentation on Oracle's Project Avatar, which allows Node.js applications to run on the Java Virtual Machine (JVM). Some key points covered include: - Avatar bridges Node.js and Java/Java EE so that Node.js apps can leverage Java libraries and infrastructure like application servers. - It provides 95% Node.js compatibility and supports running popular Node.js packages/modules. - Avatar 2.0 adds enterprise features like advanced multithreading, state sharing, persistence, and Java EE interoperability. - The architecture allows Node.js code to run alongside Java code on the JVM with access to Java APIs.

java8javascriptnodejs
Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS

This document provides an overview of AngularJS, including: - Core concepts like MVC pattern, data binding, dependency injection, modules, controllers, scopes, services, filters and directives - When to use AngularJS for CRUD and single-page applications versus when not to for games or non-SPA apps - Next steps like learning JavaScript fundamentals, reading documentation, doing tutorials, and checking out tools like Yeoman and Batarang - A sample AngularJS application is demonstrated

angular jsobject oriented javascripttechnopark
QUESTIONS
https://github.com/jovanvidic/javascript-refactoring
vidicj@gmail.com
@_yowan_
?

More Related Content

What's hot

Diseño de APIs con Ruby
Diseño de APIs con RubyDiseño de APIs con Ruby
Diseño de APIs con Ruby
Software Guru
 
React Native
React NativeReact Native
React Native
Craig Jolicoeur
 
The Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember AppsThe Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember Apps
Jesse Cravens
 
Modern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on RailsModern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on Rails
Jonathan Johnson
 
A tour of React Native
A tour of React NativeA tour of React Native
A tour of React Native
Tadeu Zagallo
 
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
Applitools
 
How to React Native
How to React NativeHow to React Native
How to React Native
Dmitry Ulyanov
 
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native
Darren Cruse
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action
Hazem Saleh
 
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
JAX London
 
[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration
Kazuchika Sekiya
 
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon RitterJava Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
JAX London
 
Agile toolkit present 2012
Agile toolkit present 2012Agile toolkit present 2012
Agile toolkit present 2012
Romans Malinovskis
 
Angularjs Tutorial for Beginners
Angularjs Tutorial for BeginnersAngularjs Tutorial for Beginners
Angularjs Tutorial for Beginners
rajkamaltibacademy
 
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.ioContinuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Mike Fotinakis
 
Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011
Jacob Kaplan-Moss
 
Creating books app with react native
Creating books app with react nativeCreating books app with react native
Creating books app with react native
Ali Sa'o
 
BPM-2 Introduction to Advanced Workflows
BPM-2 Introduction to Advanced WorkflowsBPM-2 Introduction to Advanced Workflows
BPM-2 Introduction to Advanced Workflows
Alfresco Software
 
React native
React nativeReact native
React native
Omid Nikrah
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Matt Raible
 

What's hot (20)

Diseño de APIs con Ruby
Diseño de APIs con RubyDiseño de APIs con Ruby
Diseño de APIs con Ruby
 
React Native
React NativeReact Native
React Native
 
The Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember AppsThe Art and Science of Shipping Ember Apps
The Art and Science of Shipping Ember Apps
 
Modern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on RailsModern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on Rails
 
A tour of React Native
A tour of React NativeA tour of React Native
A tour of React Native
 
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
 
How to React Native
How to React NativeHow to React Native
How to React Native
 
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native
 
Apache Cordova In Action
Apache Cordova In ActionApache Cordova In Action
Apache Cordova In Action
 
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
 
[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration[English version] JavaFX and Web Integration
[English version] JavaFX and Web Integration
 
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon RitterJava Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
Java Core | JavaFX 2.0: Great User Interfaces in Java | Simon Ritter
 
Agile toolkit present 2012
Agile toolkit present 2012Agile toolkit present 2012
Agile toolkit present 2012
 
Angularjs Tutorial for Beginners
Angularjs Tutorial for BeginnersAngularjs Tutorial for Beginners
Angularjs Tutorial for Beginners
 
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.ioContinuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
Continuous Visual Integration - RailsConf 2016 - Mike Fotinakis - Percy.io
 
Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011Writing great documentation - CodeConf 2011
Writing great documentation - CodeConf 2011
 
Creating books app with react native
Creating books app with react nativeCreating books app with react native
Creating books app with react native
 
BPM-2 Introduction to Advanced Workflows
BPM-2 Introduction to Advanced WorkflowsBPM-2 Introduction to Advanced Workflows
BPM-2 Introduction to Advanced Workflows
 
React native
React nativeReact native
React native
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
 

Viewers also liked

Redefining Projects For an Age of Complexity
Redefining Projects For an Age of ComplexityRedefining Projects For an Age of Complexity
Redefining Projects For an Age of Complexity
Jovan Vidić
 
How To Start Agile Competence Center
How To Start Agile Competence CenterHow To Start Agile Competence Center
How To Start Agile Competence Center
Jovan Vidić
 
LA COLUMNA VERTEBRAL
LA COLUMNA VERTEBRALLA COLUMNA VERTEBRAL
LA COLUMNA VERTEBRAL
iesoteropedrayoef
 
5 Games for Effective Agile Coaching
5 Games for Effective Agile Coaching5 Games for Effective Agile Coaching
5 Games for Effective Agile Coaching
Jovan Vidić
 
La Higiene Postural
La Higiene PosturalLa Higiene Postural
La Higiene Postural
guest261b8
 
Higiene Postural 2º ESO
Higiene Postural 2º ESOHigiene Postural 2º ESO
Higiene Postural 2º ESO
Lorena Delgado Raimundez
 
Higiene postural[1]
Higiene postural[1]Higiene postural[1]
Higiene postural[1]
Henry Leiva
 
Capacitacion higiene postural
Capacitacion higiene posturalCapacitacion higiene postural
Capacitacion higiene postural
Paula Caicedo Lara
 
Enfermedades ocupacionales
Enfermedades ocupacionalesEnfermedades ocupacionales
Enfermedades ocupacionales
aguzmanvel
 
Higiene postural
Higiene posturalHigiene postural
Higiene postural
Marta Gómez
 
Higiene postural y pausas activas
Higiene postural y pausas activasHigiene postural y pausas activas
Higiene postural y pausas activas
oscarruiz254
 
Principales enfermedades causadas por una mala postura corporal
Principales enfermedades causadas por una mala postura corporalPrincipales enfermedades causadas por una mala postura corporal
Principales enfermedades causadas por una mala postura corporal
Suny Sanchez
 
Ergonomía higiene postural
Ergonomía  higiene posturalErgonomía  higiene postural
Ergonomía higiene postural
vicaaron
 
Taller de higiene postural
Taller de higiene posturalTaller de higiene postural
Taller de higiene postural
juanjoreverte
 

Viewers also liked (14)

Redefining Projects For an Age of Complexity
Redefining Projects For an Age of ComplexityRedefining Projects For an Age of Complexity
Redefining Projects For an Age of Complexity
 
How To Start Agile Competence Center
How To Start Agile Competence CenterHow To Start Agile Competence Center
How To Start Agile Competence Center
 
LA COLUMNA VERTEBRAL
LA COLUMNA VERTEBRALLA COLUMNA VERTEBRAL
LA COLUMNA VERTEBRAL
 
5 Games for Effective Agile Coaching
5 Games for Effective Agile Coaching5 Games for Effective Agile Coaching
5 Games for Effective Agile Coaching
 
La Higiene Postural
La Higiene PosturalLa Higiene Postural
La Higiene Postural
 
Higiene Postural 2º ESO
Higiene Postural 2º ESOHigiene Postural 2º ESO
Higiene Postural 2º ESO
 
Higiene postural[1]
Higiene postural[1]Higiene postural[1]
Higiene postural[1]
 
Capacitacion higiene postural
Capacitacion higiene posturalCapacitacion higiene postural
Capacitacion higiene postural
 
Enfermedades ocupacionales
Enfermedades ocupacionalesEnfermedades ocupacionales
Enfermedades ocupacionales
 
Higiene postural
Higiene posturalHigiene postural
Higiene postural
 
Higiene postural y pausas activas
Higiene postural y pausas activasHigiene postural y pausas activas
Higiene postural y pausas activas
 
Principales enfermedades causadas por una mala postura corporal
Principales enfermedades causadas por una mala postura corporalPrincipales enfermedades causadas por una mala postura corporal
Principales enfermedades causadas por una mala postura corporal
 
Ergonomía higiene postural
Ergonomía  higiene posturalErgonomía  higiene postural
Ergonomía higiene postural
 
Taller de higiene postural
Taller de higiene posturalTaller de higiene postural
Taller de higiene postural
 

Similar to Refactoring JavaScript Applications

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
Avatar 2.0
Avatar 2.0Avatar 2.0
Avatar 2.0
David Delabassee
 
Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS
Deepu S Nath
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
 
BPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to ActivitiBPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to Activiti
Alfresco Software
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
musaibasrar
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
hchen1
 
How I learned to stop worrying and love embedding JavaScript
How I learned to stop worrying and love embedding JavaScriptHow I learned to stop worrying and love embedding JavaScript
How I learned to stop worrying and love embedding JavaScript
Kevin Read
 
Embedding V8 in Android apps with Ejecta-V8
Embedding V8 in Android apps with Ejecta-V8Embedding V8 in Android apps with Ejecta-V8
Embedding V8 in Android apps with Ejecta-V8
Kevin Read
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
Hazem Saleh
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
rajdeep
 
Unlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin ArchitectureUnlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin Architecture
Matt Nolan
 
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2
 
WSO2 AppDev platform
WSO2 AppDev platformWSO2 AppDev platform
WSO2 AppDev platform
Sagara Gunathunga
 
Developer Productivity with Forge, Java EE 6 and Arquillian
Developer Productivity with Forge, Java EE 6 and ArquillianDeveloper Productivity with Forge, Java EE 6 and Arquillian
Developer Productivity with Forge, Java EE 6 and Arquillian
Ray Ploski
 
Server Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David DelabasseeServer Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David Delabassee
JAXLondon2014
 
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript AppsIn Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
Spike Brehm
 

Similar to Refactoring JavaScript Applications (20)

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Avatar 2.0
Avatar 2.0Avatar 2.0
Avatar 2.0
 
Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
BPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to ActivitiBPM-4 Migration from jBPM to Activiti
BPM-4 Migration from jBPM to Activiti
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
How I learned to stop worrying and love embedding JavaScript
How I learned to stop worrying and love embedding JavaScriptHow I learned to stop worrying and love embedding JavaScript
How I learned to stop worrying and love embedding JavaScript
 
Embedding V8 in Android apps with Ejecta-V8
Embedding V8 in Android apps with Ejecta-V8Embedding V8 in Android apps with Ejecta-V8
Embedding V8 in Android apps with Ejecta-V8
 
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
[JMaghreb 2014] Developing JavaScript Mobile Apps Using Apache Cordova
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
 
Unlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin ArchitectureUnlocking the power of the APEX Plugin Architecture
Unlocking the power of the APEX Plugin Architecture
 
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
 
WSO2 AppDev platform
WSO2 AppDev platformWSO2 AppDev platform
WSO2 AppDev platform
 
Developer Productivity with Forge, Java EE 6 and Arquillian
Developer Productivity with Forge, Java EE 6 and ArquillianDeveloper Productivity with Forge, Java EE 6 and Arquillian
Developer Productivity with Forge, Java EE 6 and Arquillian
 
Server Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David DelabasseeServer Side JavaScript on the Java Platform - David Delabassee
Server Side JavaScript on the Java Platform - David Delabassee
 
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript AppsIn Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
 

Recently uploaded

Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
Mitchell Marsh
 
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
onemonitarsoftware
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Asher Sterkin
 
Migrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS CloudMigrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS Cloud
Ortus Solutions, Corp
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
onemonitarsoftware
 
ThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and DjangoThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and Django
akshesh doshi
 
Google ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learningGoogle ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learning
VishrutGoyani1
 
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
avufu
 
NYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdfNYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdf
AUGNYC
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
miso_uam
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
sudsdeep
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
ThousandEyes
 
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
Semiosis Software Private Limited
 
Intro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AIIntro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AI
Ortus Solutions, Corp
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
What is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for FreeWhat is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for Free
TwisterTools
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdfdachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
DNUG e.V.
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
Task Tracker
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
ssuser2b426d1
 

Recently uploaded (20)

Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
 
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
 
Migrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS CloudMigrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS Cloud
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
 
ThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and DjangoThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and Django
 
Google ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learningGoogle ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learning
 
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
 
NYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdfNYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdf
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
 
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
 
Intro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AIIntro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AI
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
What is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for FreeWhat is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for Free
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
 
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdfdachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
 

Refactoring JavaScript Applications

  • 1. codecentric d.o.o Jovan Vidić, IT Consultant @ codecentric Refactoring Java Script Applications
  • 2. Motivation Should We Refactor JavaScript? Refactoring Sample Application Beyond Refactoring Agenda
  • 3. ~ 6 years of development Java + DWR 732 JavaScript files ~ 20 000 lines of javascript code Motivation - Legacy project
  • 4. What was wrong? - JavaScript in HTML - Global functions - Inline styles - No coding style guidelines - No tests MOTIVATION - Legacy project
  • 5. What was OK? - OOP - Throwing own errors - Wrapping third party libraries - Prototype.js MOTIVATION - Legacy project
  • 6. Should We Refactor JavaScript ?
  • 7. “It is not necessary to change. Survival is not mandatory” W. Edwards Deming W E Deming
  • 9. What is Refactoring? a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior M. Fowler
  • 10. This is not refactoring
  • 11. agile manifesto 8th principle Agile processes promote sustainable development. The sponsors, developers, and users should be able to maintain a constant pace indefinitely.
  • 12. Refactoring Sample Application – v1 – index.html </head>! <body>! <ul class="nav nav-pills">! <li class="active"><a href="../../v1/client/index.html">V1</a></ li>! <li><a href="../../v2/client/index.html">V2</a></li>! <li><a href="../../v3/client/index.html">V3</a></li>! <li><a href="../../v4/client/index.html">V4</a></li>! <li><a href="../../v5/client/index.html">V5</a></li>! </ul>! <div class="page-header">! <h1>Coding Serbia <small> Refactoring JavaScript Applications - V1</small></h1>! </div>! <!-- Button trigger modal -->! <button class="btn btn-primary btn-lg" data-toggle="modal" onclick="createSpeaker()">! Add Speaker! </button>!
  • 13. <script src="js/jquery.min.js"></script>! <script src="js/bootstrap.min.js"></script>! <script src="js/speakers.js"></script>! ! <script type="text/javascript">! load();! </script>! </body>! Refactoring Sample Application – v1 – index.html
  • 14. Refactoring Sample Application – v1 – speakers.js function add() {! var speakerId = $('#speakerId').val();! ! $.ajax({! type: speakerId == '' ? "POST" : "PUT",! url: speakerId == '' ? "http://localhost:4730/speakers" : "http:/! data: JSON.stringify({id: speakerId, firstName: $('#firstName').v! contentType: "application/json; charset=utf-8",! dataType: "json",! success: function(data){ $('#speakerId').val(''); $('#firstName’)! failure: function(errMsg) {alert(errMsg);}! ! function load() {! $.getJSON( "http://localhost:4730/speakers", function( data ) {! var newRows = "";! $.each(data, function(i,item) {! var sessionTime = new Date(Date.parse(item.sessionTime));! ! newRows += "<tr><td>" + sessionTime.toLocaleString() +"</td><! });! $(".table-striped tbody").html("");! $(".table-striped tbody").append(newRows);! });! };!
  • 15. Refactoring Sample Application – v1 It is a complete mess! How should I start?
  • 16. Refactoring Sample Application – v1 – selenium
  • 17. Refactoring Sample Application – v1 What about JSLint/JSHIT?
  • 18. It will scream at you!
  • 19. Refactoring Sample Application – v2 Invert dependencies
  • 20. Refactoring Sample Application – v2 - REQUIREJS requirejs.config({! paths: {! "jquery": "lib/jquery.min",! "bootstrap": "lib/bootstrap.min"! },! shim: {! "bootstrap": {! deps: ["jquery"]! }! }! });! ! require(["app/speakers","bootstrap"], function (speakers) {! ! $("#btnSaveSpeaker").click(function() {! speakers.save();! });! ! speakers.loadAll();! });! <script data-main="scripts/main" src="scripts/lib/require.js"></script>!
  • 21. Refactoring Sample Application – V2 – SPEAKERS.JS & THEME.jS define(["jquery","app/theme"], function ($, theme) {! "use strict";! ! var SpeakerControler = {! loadAll : function () {! $.getJSON("http://localhost:4730/speakers", function (data) {! var speakersTable = $("." + theme.SPEAKERS_TABLE +" tbody") define([], function () {! "use strict";! ! return {! DELETE_BUTTON : "btn btn-danger glyphicon glyphicon-remove",! EDIT_BUTTON : "btn btn-default glyphicon glyphicon-pencil",! SPEAKERS_TABLE : "table-striped"! };! });!
  • 22. Refactoring Sample Application – SPEAKERS.JS define(["jquery","app/theme"], function ($, theme) {! "use strict";! ! var SpeakerControler = {! loadAll : function () {! cell.append($("<button class='"+theme.DELETE_BUTTON+"'></button>”)! SpeakerControler.remove(item.id);! })); remove : function(id) {! $.ajax({! type: "DELETE",! url: "http://localhost:4730/speaker/" + id,! success: function() {! SpeakerControler.loadAll();! }! });! }! return SpeakerControler;! });
  • 23. My code is isolated now Can I write unit tests?
  • 25. Refactoring Sample Application – v3 Manage dependencies
  • 26. Refactoring Sample Application – v3 – bower.json {! "name": "javascript-refactoring",! "version": "1.0",! "authors": [! "Jovan Vidic <jovan.vidic@codecentric.de>"! ],! "private": true,! "ignore": [! "node_modules",! "bower_components",! "test",! "tests"! ],! "dependencies": {! "jquery": "1.11.1",! "bootstrap" : "3.2.0",! "requirejs" : "2.1.15"! },! ! "devDependencies": {! ! }! }!
  • 27. Refactoring Sample Application – v4 Improve design Introduce model objects & unit tests
  • 28. Refactoring Sample Application – v4 – MODEL.JS function Speaker(id, firstName, lastName, topic, sessionTime, track) {! this.id = id;! this.firstName = firstName;! this.lastName = lastName;! this.topic = topic;! this.sessionTime = sessionTime;! this.track = track;! ! this.hasId = function () {! return (this.id !== undefined) && (this.id !== null) ! && (this.id !== "");! };! ! this.getFullName = function () {! return this.firstName + " " + this.lastName;! };! }! ! return {! "Agenda" : {! "Speaker" : Speaker! }! };!
  • 29. Refactoring Sample Application – v4 – Speakers.JS define(["jquery", "app/model", "app/theme"], function ($, model, theme) {! "use strict";! var SpeakerControler = {! editSpeaker : function(id) {! $.getJSON( "http://localhost:4730/speaker/" + id, ! function(speakerData) {! if(speakerData) {! var speaker = convertToModel(speakerData);! showEditSpeakerPopup(speaker);! }! });! }! function showEditSpeakerPopup(speaker) {! $('#myModalLabel').html('Edit speaker <strong>' ! + speaker.getFullName() + "</strong>");! }! function convertToModel(speakerData) {! return new model.Agenda.Speaker(speakerData.id, speakerData.firstName, speakerData.lastName, speakerData.topic, speakerData.sessionTime, speakerData.track);! }
  • 30. Refactoring Sample Application – v4 – jasmine describe("Test model objects", function() {! "use strict";! ! var Model;! ! beforeEach(function(done) {! require(["app/model"], function (model) {! Model = model;! done();! });! }); it("should return Jovan Vidic when firstName is Jovan and lastName is Vidic", function() {! ! var speaker = new Model.Agenda.Speaker(1, "Jovan", "Vidic");! ! expect(speaker.getFullName()).toBe("Jovan Vidic");! });!
  • 31. Refactoring Sample Application – v4 That's all cool but my code still stinks?!
  • 32. Trust me I've been there
  • 33. Refactoring Sample Application – v5 Improve design & automate
  • 34. Refactoring Sample Application – v5 – SPEAKERS AJAX CLIENT define(["jquery", "app/model"], function ($, model) {! "use strict";! ! var baseURL = requirejs.s.contexts._.config.cs["api-url"],! speakersURL = baseURL + "speakers/",! speakerURL = baseURL + "speaker/";! ! function convertToModel(speakerData) {! return new model.Agenda.Speaker(speakerData.id, speakerData.firstNa }! return {! loadAllSpeakers : function (callbackHandle) {! $.getJSON(speakersURL, function (speakersData) {! var speakers = [];! $.each(speakersData, function (index, speakerData) {! var speaker = convertToModel(speakerData);! speakers.push(speaker);! });! callbackHandle.success(speakers);! });! },
  • 35. Refactoring Sample Application – v5 – Backend FACADE define(["app/client/speakers_ajax_client"], function (speakersClient) {! "use strict";! ! return {! loadAllSpeakers : function (callbackHandle) {! speakersClient.loadAllSpeakers(callbackHandle);! },! ! saveSpeaker : function (speaker, callbackHandle) {! speakersClient.saveSpeaker(speaker, callbackHandle);! }!
  • 36. Refactoring Sample Application – v5 - TesTS define(["squire"], function (Squire) {! "use strict";! ! var injector = new Squire(),! client = jasmine.createSpyObj("client", ["loadAllSpeakers", "saveSpeaker", "removeSpeaker"]),! callbackHandle = jasmine.createSpy("callback"),! builder = injector.mock("app/client/speakers_ajax_client”, client); ! describe("Test backend facade", function() {! ! var backend;! ! beforeEach(function(done) {! builder.require(["app/backend_facade"], function(backendFacade) backend = backendFacade;! done();! });! });! it("should loadAllSpeakers", function() {! backend.loadAllSpeakers(callbackHandle);! expect(client.loadAllSpeakers)! .toHaveBeenCalledWith(callbackHandle);! });! ! !
  • 37. Refactoring Sample Application – v5 - MVP http://warren.chinalle.com/2010/12/18/model-view-presenter/
  • 38. Refactoring Sample Application – v5 – speakers PRESENTER define(["app/backend_facade", "app/speakers/speakers_view", ! "app/events"], function (backend, SpeakersView, events) {! ! "use strict";! ! var EventManager = events.EventManager,! Actions = events.Actions;! ! function SpeakerPresenter() { ! var view = new SpeakersView(),! self;! ! return {! init : function () {! self = this;! EventManager.register(Actions.LOAD_ALL_SPEAKERS, this.loadAll);! },! loadAll : function () {! backend.loadAllSpeakers({! "success" : function (speakers) {! view.showAll(speakers);! }! });! },!
  • 39. Refactoring Sample Application – v5 – Speakers view define(["app/events", "app/components", "app/speakers/speakers_popup"], ! "use strict”;! var EventManager = events.EventManager;! ! function SpeakersView() {! var speakersTable = new components.SpeakersTable(),! createButton = new components.Button("btnAddSpeaker"),! popup = new SpeakersPopup();! ! function showCreateSpeakerDialog() {! EventManager.fire(events.Actions.SHOW_CREATE_SPEAKER);! }! function init() {! createButton.addClickListener(showCreateSpeakerDialog);! }! init();! return {! showAll : function (speakers) {! var i, len;! speakersTable.clear();! for (i = 0, len = speakers.length; i < len; i += 1) {! speakersTable.addSpeaker(speakers[i]);! }! }!
  • 40. Refactoring Sample Application – v5 – SPEAKERS POPUP define(["app/model", "app/events", "app/components"], function (model, even ! function SpeakersPopup() {! var speaker,! popup = new components.Popup("myModal"),! firstNameInput = new TextField("firstName"),! ! function saveSpeaker() {! speaker.firstName = firstNameInput.val();! speaker.lastName = lastNameInput.val();! speaker.topic = topicInput.val();! ! if (speaker.hasId()) {! EventManager.fire(events.Actions.EDIT_SPEAKER, speaker);! } else {! EventManager.fire(events.Actions.SAVE_SPEAKER, speaker);! }! }! return {! openAndSet : function (speakerToUpdate) {! speaker = speakerToUpdate;! firstNameInput.val(speaker.firstName);! lastNameInput.val(speaker.lastName);! !
  • 41. Refactoring Sample Application – v5 – components http://warren.chinalle.com/2010/12/18/model-view-presenter/ define(["jquery", "app/events", "app/theme"], function ($, events, theme) ! function TextField(id) {! var textField = $("#" + id);! return {! val : function (value) {! if (value !== undefined) {! textField.val(value);! } else {! return textField.val();! }! }! };! }! ! function SimpleButton(id) {! var button = $("#" + id);! return {! addClickListener : function (listener) {! button.click(listener);! }! };! }! !
  • 43. Refactoring Sample Application – v5 - GRUNT grunt.initConfig({! ! jslint: {! src: [! "scripts/**/*.js"! ],! ! },! ! karma: {! unit: {! configFile: "karma.conf.js"! }! },! ! copy: {! main: {! files: [! {expand: true, src: ["lib/bootstrap/dist/css/**"], dest: "dist/"},! {expand: true, src: ["lib/bootstrap/dist/fonts/**"], dest: "dist/"} {expand: true, src: ["lib/requirejs/require.js"], dest: "dist/"}! ]! }! }!
  • 44. Refactoring Sample Application – v5 - GRUNT requirejs: {! compile: {! options: {! baseUrl: "scripts/",! name: "main",! out: "dist/app-built.js”,! paths: {! app: "app/",! "jquery": "../lib/jquery/dist/jquery.min",! "bootstrap": "../lib/bootstrap/dist/js/bootstrap"! }! }! }! },! processhtml: {! options: {! data: { ! }! },! dist: {! files: {! "dist/index.html": ["index.html"]! }! }!
  • 46. Coffeescript define [], () ->! ! class Speaker! constructor: (@id, @firstName, @lastName, @topic, @sessionTime, @track) ->! ! hasId: ->! @id?.length != 0! ! fullName: ->! @firstName + " " + @lastName! ! return {"Agenda": {"Speaker" : Speaker}} !