+ All Categories
Home > Technology > Building Real-Time Applications in Ember.js

Building Real-Time Applications in Ember.js

Date post: 16-Jul-2015
Category:
Upload: steve-kinney
View: 970 times
Download: 3 times
Share this document with a friend
Popular Tags:
84
Building Real-Time Applications in Ember EmberConf 2015
Transcript

Building Real-Time Applications in Ember

EmberConf 2015

Hi. I'm Steve. @stevekinney | [email protected]

Let's talk about building real-time applications with

Ember.

This is a story about WebSockets…

It's also a story about integrating all sorts of browser functionality and

third-party code into our applications.

What even is a WebSocket?

WebSockets are an HTTP independent, bi-directional, TCP-based protocol over

port 80 standardized in 2011 by the IETF as RFC 6455.

Duh.

What are WebSockets used for?

Quick Demo

Can I actually use WebSockets?

Now, that we know everything there is to know about WebSockets,

let’s get to implementing them.

Step Zero: We need a WebSocket server, right?

A WebSocket server in fourteen lines.

var WebSocketServer = require('ws').Server; var socket = new WebSocketServer({ port: 8080 });

socket.on('connection', function(connection) { connection.on('message', function(message) { socket.broadcast(message); }); });

socket.broadcast = function(data) { this.clients.forEach(function (client) { client.send(data); }); };

What does this look like on the client?

A Traditional Examplevar socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); });

Ugh. DOM/selector-based development. #fail

—Erik Bryn

“Selector-based programming”

We can do better.

Let's try two or three different approaches.

Approach #1: A standalone controller

ember generate controller websocket

app/controllers/websocket.js

app/controllers/chatroom.js

app/routes/chatroom.js

Quick Demo

This approach works great, but it's somewhat limited.

Approach #2: Dependency Injection with Services

ember generate service websocket

installing create app/services/websocket.js create app/initializers/websocket.js

app/initializers/websocket.js

Let's move that code from the controller into our service.

rm -rf app/controllers/websocket.js

app/controllers/chatroom.js

That's it.

Approach #3: Using Socket.io

Point of Interest: Socket.io is both a server- and client-

side library.

To each her own.

Let's set up a Socket.io server

bower install sio-client

app/services/websocket.js

app/controllers/chatroom.js

🎉

Thank you.

Code example: stevekinney/emberconf-chat Twitter and Github: @stevekinney

Email: [email protected] Hire our students: http://people.turing.io/


Recommended