Wayfarer
Wayfarer

Reputation: 630

Possible scoping issue

A possible node.js/backbone.js/socket.io scoping issue I can't wrap my head around.

(snippet from) server.js

var app = express();
var server = http.createServer(app);
io = io.listen(server);

(snippet from) index.html

<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect(window.location.origin);
</script>

(snippet from) js/views/map.js

(function() {  // self invoking anonymous function so we are able to 
               // create the private variable "map" that can be shared here
var map;
var webSocket = window.socket; 

window.MapView = Backbone.View.extend({

initialize: function() {
    this.render();
    webSocket.on("marker dropped", this.propNewMarker);
},

events: {
    "click .dropmarker" : "dropMarker"
},

dropMarker: function(event) {
    console.log("This fires!!!");
    webSocket.emit('marker dropped', { my: 'data' });
},

propNewMarker: function() {
    console.log("someone dropped a marker (im in map.js)");
},

(snippet from) MapView.html

<a href="#" class="btn btn-primary dropmarker">Drop marker</a>

Behavior I am going for

Clicking on the "dropmarker" button in MapView.html should instigate the webSocket.emit action in dropMarker. (it fires off the console.log without any problems)

Tested

When I add

io.sockets.emit('marker dropped', { 'message': 'ello wurldz' });

into server.js, the propNewMarker function in map.js is fired correctly.

Preliminary conclusion

It seems that I am struggling with a scoping issue at the level of the buttonclick. I'm not able to fire a websocket event there.

Any thoughts ? or should I offer more insights in the code before this can be debugged? (tried to keep it as clean as possible)

Upvotes: 1

Views: 68

Answers (1)

JasonM
JasonM

Reputation: 761

This doesn't look like an issue with the scope but in fact how you are using the socket

In order for propNewMarker to be called the server must emit a message on marker dropped

On the server if you add

io.sockets.on('connection', function (socket) {
  socket.on('marker dropped',function(msg){
    socket.emit('marker dropped',msg);
  });
});

Then the client should respond just fine to the event. I did some testing and it looks like your scoping is just fine.

Upvotes: 1

Related Questions