balderdashy/backbone-to-sails — pull request #11 by aato (2014-12-02 09:56:38+00:00)
Title: Updated backbone-to-sails to be compatible with Sails v0.10

The biggest change was adding the ability to listen to messages sent from a specific Model (as opposed to interpreting all incoming messages in the 'comet' event). For example, to listen for messages from Twinkie:

```javascript
Backbone.on('twinkie', function ( message ) {
// Do things with message.
});
```

'comet' messages are still available and are the default if no socket message callbacks are supplied.

The only bit of visible overhead that's been added is the initBackbone() function which must be called AFTER the socket connection is made and BEFORE you begin working with Backbone. Here's an example:

```javascript
socket.on('connect', function socketReady() {
initBackbone(function() {
// Safe to start working with Backbone.
});
});
```

In order to listen for messages about a specific Model, you pass in an Object as the first argument to initBackbone() that maps Model names with callback functions that trigger a Backbone event:

```javascript
socket.on('connect', function socketReady() {
initBackbone({
twinkie : function(msg)
{
Backbone.trigger('twinkie', msg);
}
},
function() {
// Safe to start working with Backbone.
});
});
```

It's not the most elegant way to go about it but I haven't found a better way that doesn't rely on generating functions from strings using eval(). For example, it would be possible for initBackbone() to accept an array of event names:

```javascript
socket.on('connect', function socketReady() {
initBackbone(['twinkie'], function() {
// Safe to start working with Backbone.
});
});
```

which is much easier on the eyes but it would rely on using:

```javascript
var eventName = "twinkie";
var code = "Backbone.trigger('" + eventName + "', msg);"
var cb = Function('msg', code);
```

in the background. If anyone knows of a better looking way to accomplish this I'd love to hear it. Let me know what you all think!