[英]How does this Javascript make it appear that an event fired from one class, is also fired from another class?
我正在使用一个名为RiotControl
的库,并且RiotControl
拥有一组Store
实例。 它还在添加到它的每个商店上连接一些事件侦听器:
https://github.com/jimsparkman/RiotControl/blob/master/demo/todo.tag#L31
var RiotControl = {
_stores: [],
addStore: function(store) {
this._stores.push(store)
}
}
['on','one','off','trigger'].forEach(function(api){
RiotControl[api] = function() {
var args = [].slice.call(arguments)
this._stores.forEach(function(el){
el[api].apply(null, args)
})
}
})
Store
观察并触发自身事件:
https://github.com/jimsparkman/RiotControl/blob/master/demo/todostore.js#L21
function TodoStore() {
...
self.on('todo_add', function(newTodo) {
self.todos.push(newTodo)
self.trigger('todos_changed', self.todos)
})
}
在上面的示例中,商店将自行触发todos_changed
事件。 尽管如此,在RiotControl
对象上也可以观察到此事件:
https://github.com/jimsparkman/RiotControl/blob/master/demo/todo.tag#L31
// Register a listener for store change events.
RiotControl.on('todos_changed', function(items) {
self.items = items
self.update()
})
我不清楚从Store
触发该事件如何在RiotControl
上观察到。 据我所知, RiotControl
在forEach
循环中,会将在其上触发的事件调度到它管理的每个商店,这就是TodoStore
可以观察self.on('todo_add')
。 我无法弄清楚self.trigger('todos_changed')
是如何self.trigger('todos_changed')
到RiotControl
,因此在那里也可以观察到。 有人知道吗
该事件在RiotControl上是可观察到的,并且可以通过self
触发,因为该事件是通过RiotControl.addStore(todoStore)
添加到RiotControl的,该事件将其添加到_stores
,然后再applys
self
或RiotControl
上调用的任何东西。
(请参阅https://github.com/jimsparkman/RiotControl/blob/master/demo/index.html#L31 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.