📜 ⬆️ ⬇️

How to make friends Socket.IO and backbone.js

As we all know, backbone.js events are divided into two categories:


Recently, I had to solve the problem of connecting socket.io to the backbone, so much so that everything would be inside the backbone application, so that the sockets events could be declared right in the views and describe all the actions that will occur on the event.

In order not to deviate from the backbone style, I wanted to implement the ability to add a socket.io event in the same way as a DOM event - a tree, namely like this:
')
var im = Backbone.View.extend({ io_events: { 'new_message': 'newMessage' }, newMessage: function(message_data){ //do something } }); 

Long searches across the Internet have led me to a selection of less elegant methods of binding backbon and sockets, which, like, solved the problem, but not in the way we would like. I had to think for myself.

The bottom line.

In the end, a code was born that I want to share with you. Below, in fact, he and an explanation of what is happening there:

 var socket = io.connect('127.0.0.1:9999'); var SocketDelegationSkeleton = Backbone.View.extend({ _initSocketio: function(){ if(this.io_events && _.size(this.io_events) > 0) for(var io_event in this.io_events){ var method = this.io_events[io_event]; //       if (!_.isFunction(method)) { method = this[method]; //   _.bind(method, this); //     this socket.on(io_event, method); //   socket.io }else{ throw new Error(' ' + '"' + method + '"' + '  '); } } } }); 

Now each your View that will use socket.io needs to be expanded from SocketDelegationSkeleton , declare events and in initialize call _initSocketio();

 var im = SocketDelegationSkeleton.extend({ io_events: { 'new_message': 'newMessage' }, initialize: function(){ this._initSocketio(); } newMessage: function(message_data){ //do something } }); 


PROFIT!

Source: https://habr.com/ru/post/179209/


All Articles