2012-02-21 30 views
0

我正在用JavaScript,CoffeeScript和jQuery编写程序。我有一个功能是当它们从网络进入时将一些东西添加到队列中。我想要的是当某个事件被添加到这个队列中时,事件会触发另一个函数开始从队列中移除项目。什么是这样做的好方法?当在Javascript中向队列或数组添加内容时触发事件

回答

4

像这样的东西可以工作:

var Queue = { 
    listeners: [], 
    objs: [], 
    add: function(item) { 
     objs.push(item); 
     $.each(listeners, function() { 
      listeners.added(item); 
     }); 
    } 
}; 
0

或者你可以从Array继承,只是重新实现你需要的功能(constructorpush

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 
相关问题