JavaScript technologies

Patterns for large client-side applications

Horváth, Győző
senior lecturer
horvath.gyozo@inf.elte.hu

Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government

Large applications

Possible failure points of large applications

Many application function

Many component

Tight coupling between components

Loosely coupled architectures

Observability

Observable design pattern

  • registerObserver(observer)
  • unregisterObserver(observer)
  • notifyObservers()
Schematic figure of the observable design pattern
Schematic figure of the observable design pattern

Observability in Backbone

Backbone.Events

  • on()
  • off()
  • trigger()

Making an observable object

// The object
var object = {};
// Making it observable
_.extend(object, Backbone.Events);
// Subscribing with a function
object.on("alert", function(msg) {
  alert("Triggered " + msg);
});
// Triggering event
object.trigger("alert", "an event");

Observability in Backbone

Every Backbone entity have this feature:

  • Backbone
  • Backbone.Model
  • Backbone.Collection
  • Backbone.View

Problem

Subscribing to each others events, the tight coupling remains between the observable objects.

A possible solution

Communication through a central object

Central event manager pattern (aka event bus).

// The central event manager
var pubsub = _.extend({}, Backbone.Events);

Centralized event management

Centralized event handling in Backbone applications

Backbone.Radio

Backbone.Radio

npm install --save backbone.radio

Basic concepts:

  • Event
  • Command
  • Request

Events

on(), off(), trigger(), once()

listenTo(), stopListening()

Commands

comply(), stopComplying(), command(), complyOnce()

Requests

reply(), stopReplying(), request(), replyOnce()

Channels

Message segmentation

var Radio = require('backbone.radio');
var inboxChannel = Radio.channel('inbox');
inboxChannel.trigger(/*...*/);

Use cases

  • Event
    • Loose coupling of views
    • Notifying about state changes
  • Command
    • e.g. logging
    • message for a given object
  • Request
    • ensuring common resources