raphael_turtle raphael_turtle - 8 days ago 6
CoffeeScript Question

Break from a coffeescript javascript if statement

I'm using the vimeo api which reports the progress of the video playing back every second from 0.0 to 1 when the video is complete.
I want to do something when the progress is 0.66 or above but in my if loop whatever I want to do is fired continously once progress reaches 66% (0.66)

player.addEvent 'playProgress', (data, id) ->
break_loop = false
if data.percent >= 0.66 && break_loop is false
do_something
break_loop = true


From when the video is at 66% progress to finished
do_something
fires every second, how can I just run it once?

Answer

I'd recommend updating your code to use the new Vimeo JavaScript API so that you could use off to remove event handlers. Then you could move your event handler to a named function (or at least the closest thing CoffeeScript has to named functions) and that could unbind itself when the 66% mark is reached, something like:

progress = (data) ->
  return if(data.percent < 0.66)
  do_something()
  player.off('timedupdate', progress)

player.on('timedupdate', progress)

Not only do you get an up-to-date interface but you also learn a fairly common pattern with JavaScript callbacks.

There might be something like off in the old API you're using but I can't find any documentation for it.