'How does this JavaScript make it appear that an event fired from one class, is also fired from another class?
I'm working with a library called RiotControl, and RiotControl holds a collection of Store instances. It also wires up some event listeners on every store that's added to it:
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)
})
}
})
A Store observes and fires events on itself:
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)
})
}
In the above example, the store will fire a todos_changed event on itself. Somehow though, this event is also observable on the RiotControl object:
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()
})
It's unclear to me how this event is observable on RiotControl when it's fired from the Store. As far as I can tell, RiotControl, in the forEach loop, will dispatch events that are fired on it to each store it manages, and this is why TodoStore can observe self.on('todo_add'). I can't figure out how self.trigger('todos_changed') bubbles up to RiotControl though so that it's observable there as well. Anybody have any idea?
Solution 1:[1]
The event is observable on RiotControl and triggerable via self because it was added to RiotControl via RiotControl.addStore(todoStore), which adds it to _stores and then applys whatever was called on self or RiotControl later.
(see https://github.com/jimsparkman/RiotControl/blob/master/demo/index.html#L31 )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dylanrw |
