Search code examples
node.jschatnowjs-sockets

error when calling the distributeMessage method using now.js


Started playing with the now.js framework. Using the example code in now.js I'm trying to implement a chat. Including here for completeness.

<script src="http://localhost:8080/nowjs/now.js" type="text/javascript"></script>

<!-- HTML for Chat Here  -->

$(document).ready(function() {

  now.receiveMessage = function(name, message) {
    $(".chattext").append("<br>" + name + ": " + message);
    $(".chattext").attr({ scrollTop: $(".chattext").attr("scrollHeight") });
  }

  $("#send-button").click(function() {
    now.distributeMessage($("#text-input").val());
    $("#text-input").val("");
  });

  now.name = prompt("What's your name?", "")

});

I've got the node.js server with now.js working properly.

I'm trying to extend the chat so that when a user enters their name, a message is sent to the server noting that " has now joined the chat." The example code prompts a user for a name and sets that to the now object's name.

now.name = prompt("What's your name?", "");

At this point, the now object is available. So instead of simply setting the now.name, I'm trying to set the now.name AND send a message by calling distributeMessage('John has joined chat.')

var p = prompt("What's your name?", "");
if (!p) {
    // errs here
} else {
    now.name = p;
    now.distributeMessage(now.name + " has joined chat.");
}

Chrome and firefox report an error that reads

Object #<Object> has no method 'distributeMessage'.

I don't understand why. The now.name property can be set. The console log shows the object with get distributeMessage and set distributeMessage functions. I can send the message when I click on the 'send-button' element. But, I am unable to call the distributeMessage at this point.

Is the now object not fully loaded when I try to make the method call? Do I need to include some sort of 'now' onLoadReady method? What do I need to do in order to fire off the now.distributeMessage method after the prompt?


Solution

  • I've found a method to address my issue. I need to surround the call to distribute message with a

    now.ready(function() {
      now.distributeMessage(now.name + " has joined chat.");
    })
    

    It seems the client side now namespace was available but all serverside now calls still required javascript to finish processing.