blechdom
blechdom

Reputation: 25

accessing model with socket.io causes namespace error in backbone view

I have a question about using sockets in a backbone view.

How do I access the model from inside of a socket listener? I want to do something like...

window.SocketView = Backbone.View.extend({

initialize:function () {

     _.bindAll(this, 'render', 'updateModelFromServer'); 

    this.render();

},

render:function () {
    $(this.el).html(this.template());
    return this;
},

events: {

    "click #chageGlobalState"       : "updateModelFromServer"
},

updateModelFromServer: function() {

   socket.emit("globalState", 1);

   socket.on("updateState", function(data) {

        this.model.set("state", data);
    });
});

});

this results in a socket.io namespace error. What is the best way to share data between sockets and models?

Is there a simple syntax issue I am missing?

or do I need to dive deeper and use ...

an event aggregator? Backbone.ioBind? Marionette? dnode?

This project is a multimedia chat-like web application.

thanks in advance!

Upvotes: 0

Views: 118

Answers (1)

Bryan Clark
Bryan Clark

Reputation: 2602

It looks like you're trying to use the wrong this inside your socket callback.

Instead of doing this:

socket.on("updateState", function(data) {
    this.model.set("state", data);
});

Try doing this:

socket.on("updateState", function(data) {
    this.model.set("state", data);
}.bind(this));

Upvotes: 1

Related Questions