collusionbdbh collusionbdbh - 3 months ago 17
CoffeeScript Question

Ember run later in coffeescript not working correctly

I am pretty new to Ember so I am totally stumped by this. The run later appears to work however it seems to ignore the fact that it is supposed to only run once every 5 seconds to update the status, it actually seems to just continually and immediately keep calling the getServers method and then immediately call itself (startWatchingStatus) again. Because of this code the page never actually gets rendered. I must be doing something wrong in this code:

App.ServersController = Ember.ArrayController.extend(

startWatchingStatus: () ->
controller = @
controller.getServers()
Ember.run.later(controller, () ->
controller.startWatchingStatus()
, 5000)

getServers: () ->
App.ServerObject.getServers().done((data) ->
controller.set('content', data)
)

init: () ->
@_super()
controller = @
controller.startWatchingStatus()

Answer

You are misinterpreting the usage of Ember.run.later, it will wait 5000ms and then execute your method, it won't keep repeating it for you. For that you could either chain the calls to Ember.run.later like this (sorry, don't know coffescript but you'll get the idea):

var callback = () => {
  this.getServers();
  Ember.run.later(this, callback, 5000);
};

Ember.run.later(controller, callback, 5000);

Or you could go with a simple window.setInterval and wrap it within a runloop inside.

window.setInterval(()  => {
  Ember.run(() => {
    controller.getServers();
  });
}, 5000);

The second one might be easier if you need to be cancel the interval later on but it's up to you which one you prefer.