Flotype / now

NowJS makes it easy to build real-time web apps using JavaScript
http://www.nowjs.com
MIT License
1.91k stars 175 forks source link

Problem initializing "now" on dom ready #5

Closed pheuter closed 13 years ago

pheuter commented 13 years ago

Consider the following client code:

<script type="text/javascript" charset="utf-8">
now.listen = function(msg) {
  alert(msg);
}

$(document).ready(function() {
  now.send("Ha");
});
</script>

and the following server code:

everyone.now.send = (msg) ->
  everyone.now.listen msg

Upon page load, I should see an alert box popup and display "Ha". Unfortunately, this does not happen, and I get the following error in the browser console:

Uncaught TypeError: Object #<Object> has no method 'send'

If I change the client side code to:

$(document).ready(function() {
  setTimeout(function(){now.send("Ha");},1000)
});

The alert box successfully shows up and displays "Ha".

This means that nowjs does not (completely) initialize upon dom ready, requiring a few extra moments to work. This is a problem for applications that depend on nowjs behavior upon dom initialization, and setTimeout seems too hacky a work'a'round.

ericz commented 13 years ago

You can use the now.ready (which is immediately available, including at $(document).ready(), in order to make sure your code run as soon as NowJS is initialized.

This code will alert "Ha" without any type of hackery.

<script type="text/javascript" charset="utf-8">
now.listen = function(msg) {
  alert(msg);
}

$(document).ready(function() {
  now.ready(function(){
      now.send("Ha");
  });
});
</script>
ericz commented 13 years ago

Additionally, now does not begin to initialize until window.onload so there should not exist a race condition where now.ready(function(){...}) is created after now has initialized thus preventing now from calling the function.

ericz commented 13 years ago

Closing