Using websockets in Backbone.js without Socket.io

I'm new to Backbone, and I'm trying to create a Backbone application that displays and displays data in real time. I implemented websocket after this code sample. The problem is that I would like to use a more extensive dataset than the sample code, and if I understand the code, it just creates one model - one array of points. I want a set of models in which each model has latitude, longitude, and quantity (just a numerical value).

How can I implement a web layout so that when my backend sends JSON, my application creates a new model with these attributes? I read on blogs about this that I need to override Backbone.sync and implement an event aggregator, but the only examples I saw in this case use socket.io. Socket.io is not an option due to the language / structure that I use on the server. Moreover, in the end I will disable the backend in another language that is also not supported by socket.io, so I would like to find a more general way to implement websocket on an interface that does not include a library such as socket.io.

+5
source share
3 answers

, . , Backbone, , - , . Andrew Cholakian. , .

, JSON {data: "{"lat": latitude, "long": longitude, "amt": amount}"}

// this function opens the websocket and will trigger add_point when
// a new message is received
Stream = function () {
    _.extend(this, Backbone.Events);
    var self = this;

    self.socket = new WebSocket("ws://" + document.domain + ":5000/websocket");
    console.log("Using a standard websocket");

    self.socket.onopen = function(e) {
        self.trigger('open', e);
        console.log('socket opened');
    };

    self.socket.onerror = function(e) {
        self.trigger('error', e);
    };

    self.socket.onmessage = function(e) {
        self.trigger('message', e);
        self.trigger('data', e.data);
        self.trigger('add_point', JSON.parse(e.data));
    };

    self.socket.onclose = function(e) {
        self.trigger('close', e);
        console.log('socket closed');
    };
};  

DataPoint = Backbone.Model.extend({
    defaults: {
        lat: null,
        long: null,
        amt: null
        }
});

DataSet = Backbone.Collection.extend({
    model: DataPoint,
    initialize: function(options) {
        this.stream = options.stream;
        var self = this;
        this.stream.on("add_point", function(pt) {
            self.add( new DataPoint({
                lat: pt.lat,
                long: pt.long,
                amt: pt.amt
            }));
            console.log('updated collection');
            console.log(self.models);
        });
    }
});

MapView = Backbone.View.extend({
    initialize: function(options) {
        this.dataSet = options.dataSet;
    }
});

$(function() {
    var stream = new Stream();
    var dataSet = new DataSet({ stream: stream });
    var mapView = new MapView({ dataSet: dataSet });
});
+4

Backbone.WS, WebSockets. !

+1

backbone.wamp WAMP WebSocket

0

All Articles