简体   繁体   中英

Socket.io, keeping different pages from receiving every message?

Sorry about that confusing title but I didn't know how to explain my question, someone please edit it for me accordingly. So i have a website page that receives messages from node server.

socket.on('item finished', function(data){
    $('#item'+data).html('finished');
});

So basically I'm telling the client that once a item has finished, it must tell that to users. I'm putting all my js code in script.js and calling it in the pages, so I have the script in all my pages. Whenever I'm on the other pages and the servers emits 'item finished' to the client a message will pop up on console.

Uncaught TypeError: Cannot read property 'html' of null

The error isn't quite like that but You get the point, the client is trying to do what it is supposed to do, but I don't want that to happen. So is there a way to avoid console errors using the same script file in different pages? What Am I missing? Thank You!

You have several choices for messages that don't apply to a given page.

  1. Separate out the item finished message listening code into a separate script so that that script is only loaded and the listener is only active in the pages that you want to actually respond to that message.

  2. Leave it the way you have where you are listening to that message in all pages, but in the handler for that message examine the type of page you're in to decide whether you should just ignore the message or do something with it thus avoiding trying to do something with it when it's the wrong kind of page.

  3. Bulletproof the code that carries out the action so that it checks to see if the desired element exists before trying to operate on it. That could look something like this:

Code:

// You aren't supposed to have to do this in jQuery, so I'm guessing that
// you aren't actually showing us the right code or error message
// But, this is the general idea of defensive coding
socket.on('item finished', function(data){
    var target = $('#item'+data);
    if (target.length) {
        target.html('finished');
    }
});

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