• Stars
    star
    415
  • Rank 104,301 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 13 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Realtime web app framework for Backbone, socket.io and node.js

#Capsule

Capsule is an experimental web framework by @HenrikJoreteg for Node.js that uses Socket.io and Backbone.js to synchronize model state by sharing model code between the client and the server.

$ npm install capsule

MIT Licensed.

##Introduction !important

Capsule presents and experimental approach to building real-time web apps that re-uses the exact same models on the server as what you serve in a script tag in the html of your app. I've used this approach for a couple of apps, one of which our team uses everyday.

For more information on this approach see my blog post on Re-using Backbone.js Models on the server with Node.js and Socket.io to build realtime apps. It's also something I will discuss it in my upcoming talk at NodeConf 2011.

It's essentially a set of convenience methods and additions to @jashkenas's excellent Backbone.js lib. In it's current state Capsule is a bit indulgent in that it makes quite a few assumptions about your app and could certainly stand to be more generic.

##Core assumptions are as follows:

  • All synced state is stored in a root model which is kept in memory on the server (yes, this is inefficient in some ways, but completely badass in others. Please don't tell me it won't scale we're also working on tying this into @fritzy's awesome upcoming thoonk.js redis lib that will use redis for clustering/scaling).
  • Several of the methods in Capsule.View assume that you're also using ICanHaz.js and Mustache for your clientside templating.

##How to use it

The annotated source serves as temporary API documentation of what the code is capable of. You should read it as well, before you attempt to use this:

Here's how you'd start building an app based on this method:

  1. Build your models file. You'll want something like this at the top to make it possible to use on the server and in the browser:

     if (typeof require == 'undefined') {
       var exports = window,
         server = false;
     } else {
       var Capsule = require('./capsule.models'),
         _ = require('underscore')._,
         server = true;
     }
    
  2. Then add your root model that contains any child models or collections.

     exports.AppModel = Capsule.Model.extend({
       type: 'app',
       initialize: function (spec) {
         this.register();
         this.addChildCollection('members', exports.Members);
         this.addChildModel('activityLog', exports.ActivityLogPage);
       }
     });
    
  3. Set up socket.io and your node server. Here's the core of the socket.io event handlers.

     socket.on('connection', function (client) {
       var app, sessionId;
         
       // this is split out so we have a reference to it we can
       // bind and unbind on disconnect.
       function sendClientChanges(changes) {
         client.send(changes);
       }
         
       // I blast out the client templates this way, just cause we can.
       client.send({
         event: 'templates',
         templates: templates
       });
         
       client.on('disconnect', function () {
         if (app) app.unbind('publish', sendClientChanges);
       });
         
       client.on('message', function(message){
         var model, collection;
         
         switch (message.event) {
           case 'session':
              ...
                 
              // Here you'd get user based on sessionid
              // you'd also get the corresponding app state that they should have access to.
              // `require` you shared models file and inflate or instantiate your root app model
              // Then grab whatever else you need and send the intial state to the client.
              client.send({
                event: 'initial',
                app: app.xport()
              });
                     
              // bind to the root `publish` events to send any changes to this client
              app.bind('publish', sendClientChanges);
                     
              ...
                     
             break;
           case 'set':
             // obviously we want to secure this, to make sure they're allowed
             // to edit what they're editing
             app.modelGetter(message.id).set(message.change);
             break;
           case 'delete':
             model = app.modelGetter(message.id);
             if (model && model.collection) model.collection.remove(model);
             break;
           case 'add':
             collection = app.modelGetter(message.id);
             if (collection) collection.add(message.data);
             break;
         }
       });
     });
    
  4. In your client code. Do something like this.

     $(function () {
       // init our empty AppModel
       var app = window.app = new AppModel(),
         view = window.view = {},
         server;
         
       window.socket = new io.Socket();
         
       // get and send our session cookie (yes, i know httponly cookies would be more secure, but whatever it's demo)
       socket.on('connect', function() { 
         socket.send({event: 'session', cookie: $.cookie('&!')});
         console.log('connected');
       });
         
       socket.on('message', function (data) { 
         var changedModel, template;
         
         console.log('RECD:', data);
         
         switch (data.event) {
           case 'templates':
             for (template in data.templates) {
               ich.addTemplate(template, data.templates[template]);
             }
             break;
           case 'initial':
             //import app state
             app.mport(data.app);
             
             // init our root view
             view = window.view = new AppView({
               el: $('body'),
               model: app
             });
             
             view.render();
             break;
           case 'change':
             changedModel = Capsule.models[data.id];
             if (changedModel) {
               changedModel.set(data.data);
             } else {
               console.error('model not found for change event', data);
             }
             break;
           case 'add':
             Capsule.models[data.collection].add(data.data.attrs);
             break;
           case 'remove':
             changedModel = Capsule.models[data.id];
             if (changedModel && changedModel.collection) {
               changedModel.collection.remove(changedModel);
             }
             break;
         }
       });
     });
    

##Comments

I'd love to get feedback and/or pull requests on this. Or, hit me up on twitter @HenrikJoreteg.

##Roadmap

  • Starting point/convenience methods for required server and client setups described above.
  • Scaling questions: One big limitation of this approach in its current state is scaling. This library will be converted to use Thoonk.js to leverage Redis's clustering and pub/sub capabilities as a back end.
  • Better handling of offline support/flaky connections: Potentially one could build a changes queue of events if the connection is lost and then send those on reconnect.
  • Better/easier way to handle security instead of having to validate each message outside of the model structure on the server.
  • Full sample app (I've built stuff with this, but not opensourceable apps)
  • More awesome

##Change Log

  • 0.2.2
    • fixed bug in error callback code
    • added support for templateHelpers in views
    • improved test for enviroment (server/client)
    • better handling if used as CommonJS module in a browser

More Repositories

1

hjs-webpack

Helpers/presets for setting up webpack with hotloading react and ES6(2015) using Babel.
JavaScript
1,789
star
2

ICanHaz.js

A clean solution for templating with Mustache.js and jQuery or Zepto
JavaScript
837
star
3

feather-app

as light as a...
JavaScript
718
star
4

create-keyframe-animation

Generate CSS keyframe animations dynamically in the browser with JavaScript.
JavaScript
716
star
5

redux-bundler

Compose a Redux store out of smaller bundles of functionality.
JavaScript
581
star
6

fixpack

A package.json file scrubber for the truly insane.
JavaScript
461
star
7

Happy.js

$('form').isHappy() โ€“ Lightweight, extensible form validation plugin for jQuery/Zepto.js
JavaScript
412
star
8

html-parse-stringify

Parses well-formed HTML (meaning all tags closed) into an AST and back. quickly.
JavaScript
337
star
9

templatizer

Simple solution for compiling jade templates into vanilla JS functions for blazin' fast client-side use.
JavaScript
303
star
10

money-clip

For managing your client side cache. Tiny wrapper over IndexedDB supporting versioning and max age.
JavaScript
233
star
11

wildemitter

A super lightweight EventEmitter similar to what comes in Node.js, but with a support for wildcard events '*'
JavaScript
213
star
12

emoji-images

replace stuff like โค๏ธ with <img> tags of corresponding images per: http://www.emoji-cheat-sheet.com/
JavaScript
173
star
13

moonboots

A set of conventions and tools for bundle and serving clientside apps with node.js
JavaScript
159
star
14

webrtc.js

WebRTC abstraction for managing it simple to manage multiple peer connections of various types.
JavaScript
158
star
15

hubtags.com

A demo app, built with Ampersand and React as a static Native Web App
JavaScript
137
star
16

getconfig

Config file reader for node.js projects that detects environment based on NODE_ENV.
JavaScript
116
star
17

andlog

Super-simple, client-side CommonJS logging thingy
JavaScript
97
star
18

github-secret-keeper

Microservice to enable GitHub login for multiple server-less applications.
JavaScript
86
star
19

human-javascript

Book on building sanely architected JS apps
CSS
80
star
20

human-model

Strict models are a drop-in replacement for Backbone models but are far more restrictive and structured.
JavaScript
75
star
21

humanjs-sample-app

Sample app for human javascript book
JavaScript
67
star
22

milliseconds

Insanely lightweight module for converting times to milliseconds.
JavaScript
62
star
23

masters

Repo to follow along with Frontend Masters class
JavaScript
60
star
24

redux-bundler-worker-example

Redux-bundler with store and bundler running inside a worker
JavaScript
58
star
25

clientconfig

Super simple clientmodule for passing config items, such as API connection URLs, debug modes, etc from server to client.
JavaScript
56
star
26

webrtcsupport

Browser module to detect support for WebRTC and extract proper constructors.
JavaScript
55
star
27

internal-nav-helper

Helper function for handling internal navigation in Single Page Apps (SPAs) in ~250 bytes before gzip.
JavaScript
52
star
28

feather-route-matcher

featherweight url to handler matching
JavaScript
42
star
29

redux-bundler-react

Bindings for redux-bundler to React
JavaScript
37
star
30

redux-bundler-example

Example app built with redux-bundler
JavaScript
34
star
31

human-view

A smart base view for Backbone apps, to make it easy to bind collections and properties to the DOM.
JavaScript
33
star
32

humanjs

Application scaffolding and documentation repo for Human JavaScript Apps
JavaScript
32
star
33

ric-shim

requestIdleCallback shim that won't blow up if used in node.js
JavaScript
29
star
34

featherweight

JavaScript
28
star
35

reformer

Self-contained, self-rendering, self-validating forms that can only output valid data.
JavaScript
26
star
36

hapi-dummy-api

Generate dummy APIs for hapi.js, for building clientside apps before the real API is done.
JavaScript
26
star
37

worker-proof

Enables calling out to main thread from a worker to register callbacks, etc.
JavaScript
26
star
38

redux-persist-middleware

Creates Redux middleware that will lazily persist data from certain reducers, when certain actions occur.
JavaScript
26
star
39

react-internal-nav

React component with single 'onInternalNav' callback for handling clicks on <a> local to domain.
25
star
40

babel-plugin-h-children-fix

Allows use of standard babel JSX tools with virtual-dom/h
JavaScript
25
star
41

appcache-serviceworker-generator

Can generate an appcache manifest and ServiceWorker from same abstraction.
JavaScript
24
star
42

image-to-data-uri.js

Clientside module (compatible with clientmodules) that takes an image url, downloads the image and creates a data URI for caching, etc.
JavaScript
23
star
43

tryit

Module to wrap try-catch for better performance and cleaner API.
JavaScript
22
star
44

window-watcher

State object you can listen to for changes to window width.
JavaScript
19
star
45

slugger

Dead simple string slugification (a. la. django) for node and the broswer.
JavaScript
18
star
46

create-selector

Wrapper for reselect to allow deferring creation of selectors.
JavaScript
18
star
47

native-promisify-if-present

Return a promise from a callback-as-last-argument function using native a Promise, but only if native Promises exist.
JavaScript
17
star
48

jquery-sliding-message

Nice way to show messages to users
JavaScript
16
star
49

semi-static

Simple, lazy way to serve a directory of semi-static pages in express.js. Handy for building quick "static" pages inside an otherwise "dynamic" app.
JavaScript
15
star
50

key-tree-store

Simple tool for storing/retrieving objects events based hierarchical key paths.
JavaScript
14
star
51

dot-net-article

13
star
52

loading-stats

Client module for reporting real-world single page application performance back to you in your metrics.
JavaScript
13
star
53

video-recorder

Experimental browser module for recording contents of a `<video>` tag by taking dataURI snapshots of it.
JavaScript
12
star
54

set-query-string

Updates the browser's query string in place, so you can bind it to some dynamic query in your app
JavaScript
11
star
55

fluent-2016

Building a lightweight mobile-web app with React and Redux
JavaScript
11
star
56

time-counter

Dead-simple js module for drawing (or simply measuring) time countdowns or counters in js. Works in node and browser.
JavaScript
11
star
57

timple

Simple templating for service workers using valid javascript files as the template
JavaScript
11
star
58

sinks

Tools for object sync (get it?!), validation, diffing, and immutable deep setting
JavaScript
10
star
59

Yo-Moma

Nerdpoints for the best nerdy yo mama joke. Bonus points for git references.
10
star
60

joreteg.com

My new site
HTML
9
star
61

system-requirements.js

Boxed software has 'em, now the web does too.
JavaScript
9
star
62

jquery.dd

Simple replacement for select boxes that are totally css stylable
JavaScript
9
star
63

favicon-setter

Dead-simple favicon updating from JS. Plays nicely with jQuery and CommonJS but has no dependencies.
JavaScript
9
star
64

redux-bundler-worker

Utilities for running a redux-bundler app inside a worker
JavaScript
9
star
65

clientmodules

A small util for using npm to install clientside packages.
JavaScript
8
star
66

fingertips

Touch event handling for mobile web apps
JavaScript
8
star
67

columnizer

A simple tool for printing text in nice columns in the terminal.
JavaScript
8
star
68

redux-bundler-preact

Preact bindings for redux-bundler
JavaScript
8
star
69

jquery-magic-labels

Grabs content of label tag to display as placeholder inside text inputs
JavaScript
8
star
70

wake-event

Browser module for detecting when your computer wakes up from sleep. Based on Alex MacCaw's clever trick.
JavaScript
7
star
71

preact-nav-helper

Preact component for catching and handling internal links in your application.
JavaScript
7
star
72

mit.joreteg.com

license site I can link to from open source projects
HTML
6
star
73

bind-transforms

Bind models properties to properly prefixed CSS transforms in backbone/humanjs views.
JavaScript
6
star
74

humanjs-resources

Curated collection of simple modules solving specific problems relating to building single page apps.
JavaScript
6
star
75

SoundEffectManager

A simple sound effect manager for playing sounds using the awesome HTML 5 Web Audio API
JavaScript
6
star
76

library-api

Simple, restful, demo JSON API written in Hapi.js
JavaScript
6
star
77

ampersand-local-cache-mixin

Only fetch when your data is old or stale. Easily configurable localStorage cache for ampersand & backbone state objects, models, and collections.
JavaScript
6
star
78

transform-style

Apply transform style property with proper prefix to an element. For use with browserify / CommonJS.
JavaScript
5
star
79

holy-grail-ios-layout

Attempt at holy grail mobile safari layout/behavior.
JavaScript
5
star
80

edui

Codebase for edui workshop
JavaScript
5
star
81

labelr-ampersand

class outline and resources
JavaScript
5
star
82

jsconfbr

Sample code for simple webrtc demo
JavaScript
5
star
83

statey

An observable, extensible state object with derived watchable properties.
JavaScript
5
star
84

extend-object

Underscore's extend method as a standalone Common JS module.
JavaScript
5
star
85

google-cloud-signedurl-test-case

Trying to figure out how to make this work :-/
JavaScript
5
star
86

array-next

Advance to the next item in the array looping when hitting the end.
JavaScript
5
star
87

cookie-getter

Super simple, performant, clientside cookie reader and nothing else. CommonJS and clientmodules compatible.
JavaScript
5
star
88

Half-SASS

A partial SASS implementation written in CF
ColdFusion
4
star
89

add-keyup-events

Emit custom events from an input so you can do stuff like listening for "enter" and "esc" events the same way as you would "keyup".
JavaScript
4
star
90

humanjs-codealong-app

JavaScript
4
star
91

get-css-translated-position

Get position of DOM elements positioned with CSS translate
JavaScript
4
star
92

docs.humanjavascript.com

Docs site for humanjs tools
JavaScript
4
star
93

Strophe.js-Plugins

A collection of strophe plugins that let you work with native JavaScript instead of XML
JavaScript
4
star
94

wakelock-lazy-polyfill

Use nosleep.js as a lazy-loaded polyfill for WakeLock API
JavaScript
4
star
95

rollup-plugin-css

Rollup plugin for aggregating and outputting CSS
JavaScript
4
star
96

labelr

JavaScript
3
star
97

dob-to-age

Determines current age based on a date of birth string YYYY-MM-DD using same weird logic we humans do.
JavaScript
3
star
98

reality

Physics simulation runner for web UIs
JavaScript
3
star
99

dotnet-dashboard.andbang.com

A team dashboard app for And Bang 2.0
JavaScript
3
star
100

parse-dob

Turn a wide range of freeform inputs describing someone's birth date into `YYYY-MM-DD` using locale to get proper day / month order.
JavaScript
3
star