I am writing a program in Javascript, CoffeeScript and jQuery to be exact. I have one function that is adding things to a queue as they come in from the network. What I want is for when something is added to this queue for an event to fire to tell another function to start removing items from the queue. What would be a good way to do this?
2 Answers
Or you could inherit from Array and just reimplement the functions that you need (constructorand push)
class Queue extends Array constructor : (args...) -> @_listeners = [] super(args...) onAdd : (fn) -> @_listeners.push fn push : (args...) -> fn(args...) for fn in @_listeners super(args...) # Use it like this : q = new Queue q.onAdd (args...) -> console.log("l1", args) q.onAdd (args...) -> console.log("l2", args) q.push(32) q.push(52) console.log '-' for v in q console.log v # Output : # # l1 [ 32 ] # l2 [ 32 ] # l1 [ 52 ] # l2 [ 52 ] # - # 32 # 52