Posts Tagged ‘RealTimeWeb’
[DevoxxFR2013] Developing Modern Web Apps with Backbone.js: A Live-Coded Journey from Empty Directory to Production-Ready SPA
Lecturer
Sylvain Zimmer represents the rare fusion of hacker spirit and entrepreneurial vision. In 2004, he launched Jamendo, which grew into the world’s largest platform for Creative Commons-licensed music, proving that open content could sustain a viable business model and empower artists globally. He co-founded Joshfire, a Paris-based agency specializing in connected devices and IoT solutions, and TEDxParis, democratizing access to transformative ideas. His competitive prowess shone in 2011 when his team won the Node Knockout competition in the Completeness category with Chess@home — a fully distributed chess AI implemented entirely in JavaScript, showcasing the language’s maturity for complex, real-time systems. Recognized as one of the first Google Developer Experts for HTML5, Sylvain recently solved a cryptographically hidden equation embedded in a Chromebook advertisement, demonstrating his blend of technical depth and puzzle-solving acumen. His latest venture, Pressing, continues his pattern of building elegant, user-centric solutions that bridge technology and human needs.
Abstract
In this intensely practical, code-only presentation, Sylvain Zimmer constructs a fully functional single-page application using Backbone.js from an empty directory to a polished, interactive demo in under thirty minutes. He orchestrates a modern frontend toolchain including Yeoman for project scaffolding, Grunt for task automation, LiveReload for instantaneous feedback, RequireJS for modular dependency management, and a curated selection of Backbone extensions to address real-world complexity. The session is a masterclass in architectural decision-making, demonstrating how to structure code for maintainability, scalability, and testability while avoiding the pitfalls of framework bloat. Attendees witness the evolution of a simple task manager into a sophisticated, real-time collaborative application, learning not just Backbone’s core MVC patterns but the entire ecosystem of best practices that define professional frontend engineering in the modern web era.
The Modern Frontend Development Loop: Zero Friction from Code to Browser
Sylvain initiates the journey with yo backbone, instantly materializing a complete project structure:
app/
scripts/
models/ collections/ views/ routers/
styles/
index.html
Gruntfile.js
This scaffold is powered by Yeoman, which embeds Grunt as the task runner and LiveReload for automatic browser refresh. Every file save triggers a cascade of actions — CoffeeScript compilation, Sass preprocessing, JavaScript minification, and live injection into the browser — creating a development feedback loop with near-zero latency. This environment is not a convenience; it is a fundamental requirement for maintaining flow state and rapid iteration in modern web development.
Backbone Core Concepts: Models, Collections, Views, and Routers in Harmony
The application begins with a Task model that encapsulates state and behavior:
var Task = Backbone.Model.extend({
defaults: {
title: '',
completed: false,
priority: 'medium'
},
toggle: function() {
this.save({ completed: !this.get('completed') });
},
validate: function(attrs) {
if (!attrs.title.trim()) return "Title required";
}
});
A TaskList collection manages persistence and business logic:
var TaskList = Backbone.Collection.extend({
model: Task,
localStorage: new Backbone.LocalStorage('tasks-backbone'),
completed: function() { return this.where({completed: true}); },
remaining: function() { return this.where({completed: false}); },
comparator: 'priority'
});
The TaskView handles rendering and interaction using Underscore templates:
var TaskView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#task-template').html()),
events: {
'click .toggle': 'toggleCompleted',
'dblclick label': 'edit',
'blur .edit': 'close',
'keypress .edit': 'updateOnEnter'
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.$el.toggleClass('completed', this.model.get('completed'));
return this;
}
});
An AppRouter enables clean URLs and state management:
var AppRouter = Backbone.Router.extend({
routes: {
'': 'index',
'tasks/:id': 'show',
'filter/:status': 'filter'
},
index: function() { /* render all tasks */ },
filter: function(status) { /* update collection filter */ }
});
RequireJS: Enforcing Modularity and Asynchronous Loading Discipline
Global scope pollution is eradicated through RequireJS, configured in main.js:
require.config({
paths: {
'jquery': 'libs/jquery',
'underscore': 'libs/underscore',
'backbone': 'libs/backbone',
'localstorage': 'libs/backbone.localStorage'
},
shim: {
'underscore': { exports: '_' },
'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }
}
});
Modules are defined with explicit dependencies:
define(['views/task', 'collections/tasks'], function(TaskView, taskList) {
return new TaskView({ collection: taskList });
});
This pattern ensures lazy loading, parallel downloads, and clear dependency graphs, critical for performance in large applications.
Backbone Extensions: Scaling from Prototype to Enterprise with Targeted Plugins
Backbone’s minimalism is a feature, not a limitation. Sylvain integrates extensions judiciously:
- Backbone.LayoutManager: Manages nested views and layout templates, preventing memory leaks
- Backbone.Paginator: Implements infinite scrolling with server or client pagination
- Backbone.Relational: Handles one-to-many and many-to-many relationships with cascading saves
- Backbone.Validation: Enforces model constraints with customizable error messages
- Backbone.Stickit: Provides declarative two-way data binding for forms
- Backbone.IOBind: Synchronizes models in real-time via Socket.IO
He demonstrates a live collaboration feature: when one user completes a task, a WebSocket event triggers an immediate UI update for all connected clients, showcasing real-time capabilities without server polling.
Architectural Best Practices: Building for the Long Term
The final application adheres to rigorous principles:
- Single responsibility principle: Each view manages exactly one DOM element
- Event-driven architecture: No direct DOM manipulation outside views
- Separation of concerns: Models handle business logic, views handle presentation
- Testability: Components are framework-agnostic and unit-testable with Jasmine or Mocha
- Progressive enhancement: Core functionality works without JavaScript
Sylvain stresses that Backbone is a foundation, not a monolith — choose extensions based on specific needs, not trends.
Ecosystem and Learning Resources
He recommends Addy Osmani’s Backbone Fundamentals as the definitive free guide, the official Backbone.js documentation for reference, and GitHub for discovering community plugins. Tools like Marionette.js (application framework) and Thorax (Handlebars integration) are highlighted for larger projects.
The Broader Implications: Backbone in the Modern Frontend Landscape
While newer frameworks like Angular and React dominate headlines, Backbone remains relevant for its predictability, flexibility, and small footprint. It teaches fundamental MVC patterns that translate to any framework. Sylvain positions it as ideal for teams needing fine-grained control, gradual adoption, or integration with legacy systems.
Conclusion: From Demo to Deployable Reality
In under thirty minutes, Sylvain has built a production-ready SPA with real-time collaboration, offline storage, and modular architecture. He challenges attendees to fork the code, extend it, and ship something real. The tools are accessible, the patterns are proven, and the only barrier is action.
Links
[DevoxxFR2013] Soon, in a Galaxy Not So Far Away: Real-Time Web with Play 2, Akka, and Spaceships
Lecturer
Mathieu Ancelin is a software engineer at SERLI, specializing in Java EE technologies with a particular focus on component frameworks. He contributes to open-source projects such as GlassFish, JOnAS, and leads initiatives like CDI-OSGi and Play CDI. A member of the JSR 346 expert group for CDI 1.1, Ancelin regularly teaches at the University of La Rochelle and Poitiers, and speaks at conferences including JavaOne and Solutions Linux. He is active in the Poitou-Charentes JUG and can be followed on Twitter as @TrevorReznik.
Abstract
Mathieu Ancelin demystifies Play 2’s real-time capabilities, answering the perennial question: “WTF are Iteratees?” Through live demonstrations of two playful applications—a multiplayer spaceship battle and a real-time roulette game—he showcases how Play 2 leverages Iteratees, Akka actors, Server-Sent Events (SSE), WebSockets, HTML5 Canvas, and even webcam input to build responsive, interactive web experiences. The session explores how these APIs integrate seamlessly with Java and Scala, enabling developers to create low-latency, event-driven systems using their preferred language. Beyond the fun, Ancelin analyzes architectural patterns for scalability, backpressure handling, and state management in real-time web applications.
Demystifying Iteratees: Functional Streams for Non-Blocking I/O
Ancelin begins by addressing the confusion surrounding Iteratees, a functional reactive programming abstraction in Play 2. Unlike traditional imperative streams, Iteratees separate data production, processing, and consumption, enabling composable, backpressure-aware pipelines.
val enumeratee: Enumeratee[Array[Byte], String] = Enumeratee.map[Array[Byte]].apply[String] { bytes =>
new String(bytes, "UTF-8")
}
This allows safe handling of chunked HTTP input without blocking threads. When combined with Enumerators (producers) and Enumeratees (transformers), they form robust data flows:
val socket: WebSocket[JsValue, JsValue] = WebSocket.using[JsValue] { request =>
val in = Iteratee.foreach[JsValue](msg => actor ! msg).map(_ => actor ! PoisonPill)
val out = Enumerator.fromCallback1(_ => futurePromise.future)
(in, out)
}
Ancelin demonstrates how this pattern prevents memory leaks and thread exhaustion under load.
Akka Actors: Coordinating Game State and Player Actions
The spaceship game uses Akka actors to manage shared game state. A central GameActor maintains positions, velocities, and collisions:
class GameActor extends Actor {
var players = Map.empty[String, Player]
val ticker = context.system.scheduler.schedule(0.millis, 16.millis, self, Tick)
def receive = {
case Join(id, out) => players += (id -> Player(out))
case Input(id, thrust, rotate) => players(id).update(thrust, rotate)
case Tick => broadcastState()
}
}
Each client connects via WebSocket, sending input events and receiving rendered frames. The actor model ensures thread-safe updates and natural distribution.
Real-Time Rendering with Canvas and Webcam Integration
The game renders on HTML5 Canvas using client-side JavaScript. Server pushes state via SSE or WebSocket; client interpolates between ticks for smooth 60 FPS animation.
A bonus feature uses getUserMedia() to capture webcam input, mapping head tilt to ship rotation—an engaging demo of sensor fusion in the browser.
navigator.getUserMedia({ video: true }, stream => {
video.src = URL.createObjectURL(stream);
tracker.on('track', event => sendRotation(event.data.angle));
});
Play Roulette: SSE for Unidirectional Live Updates
The second demo, Play Roulette, uses Server-Sent Events to broadcast spin results to all connected clients:
def live = Action {
Ok.chunked(results via EventSource()).as("text/event-stream")
}
Clients subscribe with:
const es = new EventSource('/live');
es.onmessage = e => updateWheel(JSON.parse(e.data));
This pattern excels for broadcast scenarios—news feeds, dashboards, live sports.
Language Interoperability: Java and Scala Working Together
Ancelin emphasizes Play 2’s dual-language support. Java developers use the same APIs via wrappers:
public static WebSocket<JsonNode> socket() {
return WebSocket.withActor(GameActor::props);
}
This lowers the barrier for Java teams adopting reactive patterns.
Architecture Analysis: Scalability, Fault Tolerance, and Deployment
The system scales horizontally using Akka clustering. Game instances partition by room; a load balancer routes WebSocket upgrades. Failure recovery leverages supervisor strategies.
Deployment uses Play’s dist task to generate start scripts. For production, Ancelin recommends Typesafe ConductR or Docker with health checks.
Implications for Modern Web Applications
Play 2’s real-time stack enables:
– Low-latency UX without polling
– Efficient resource use via non-blocking I/O
– Graceful degradation under load
– Cross-language development in polyglot teams
From games to trading platforms, the patterns apply broadly.
Links:
[DevoxxBE2013] Java EE 7’s Java API for WebSocket
Arun Gupta, Director of Developer Advocacy at Red Hat, unveils the transformative capabilities of the Java API for WebSocket in Java EE 7. A veteran of Sun Microsystems and Oracle, Arun has championed Java technologies globally, authoring extensive blogs and a best-selling book. His session explores WebSocket’s role in enabling efficient, bidirectional communication, eliminating the need for long polling or AJAX. Through live demonstrations, he illustrates server-side endpoints and client-side integrations, showcasing how this API empowers developers to craft responsive web and rich client applications.
WebSocket, a cornerstone of HTML5, facilitates real-time data exchange over a single TCP connection. Arun highlights its scalability, with GlassFish handling thousands of connections, and introduces tools like Autobahn for compliance testing. This API positions Java developers to build dynamic, scalable systems that complement RESTful architectures.
WebSocket Fundamentals and API Design
Arun introduces WebSocket’s departure from HTTP’s request-response model, leveraging a single, persistent connection. Using annotations like @ServerEndpoint, he demonstrates creating a chat application where messages flow instantly. The client API, accessible from browsers or Java applications, enables seamless integration.
This simplicity, Arun notes, reduces latency, making WebSocket ideal for real-time applications like live updates or collaborative tools.
Server-Side Scalability and Performance
Scalability is a key strength, Arun explains, with WebSocket supporting millions of file descriptors on Linux. He recounts Oracle’s GlassFish tests, achieving robust performance with thousands of connections. The Autobahn test suite, he suggests, validates compliance and load capacity.
Forthcoming WildFly tests, Arun adds, will further benchmark performance, ensuring reliability in production environments.
Complementing REST with WebSocket
Arun clarifies that WebSocket complements JAX-RS, not replaces it. He illustrates a hybrid design: REST for stateless queries, WebSocket for real-time updates. A stock ticker demo shows prices pushed to clients, blending both paradigms.
This synergy, Arun argues, enhances application flexibility, with Java EE 8 discussions exploring further integrations.
Community Engagement and Future Directions
Arun encourages joining Java EE expert groups, noting their transparent processes. Recent community gatherings, he mentions, discussed enhancing WebSocket’s role. He advocates contributing to shape Java EE 8, ensuring it meets developer needs.
This collaborative approach, Arun emphasizes, drives innovation, aligning WebSocket with evolving web standards.