简体   繁体   中英

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 function in 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM