Reputation: 1
I have a different implementation of cross-component communication here http://jsfiddle.net/c641oog2/ than what's described here: http://lhorie.github.io/mithril/components.html#librarization. The goal is to create an easily integrable & scalable (to be re-used in other components) components, i.e librarization.
Main parts of my code:
var autocompleter = function(options) {
...
autocompleter.vm = {
list: m.prop(options.list || []),
observers: m.prop(options.observers || []),
...
select: function(item) {
for(observer in autocompleter.vm.observers()) {
autocompleter.vm.observers()[observer](item); //notify all observers of selection
}
}
//initialization later on...
this.userAC = new autocompleter({list: this.users(), observers: [this.selectedUser]})
The main difference is in how the components communicate with each other. In my implementation, I decided to use observers, and in the documentation's implementation, he has implemented by creating pure functions which are then used in the "view" function of dashboard, where correct arguments are passed to the "view" function of the autocomplete function.
My questions:
Upvotes: 0
Views: 1234
Reputation: 1420
Personally, I prefer the 'pure' version, rather than the observer pattern. I think that conceptually it's simpler. There's no cross-component communication, it's all vertical up and down between parents and children.
Also, you then break (in my mind) the idea that UI state is data, and so ideally never duplicated.
It means that if you create new components that want to interact with the rest, they all need to keep copies of the selected state, rather than all observing the single UI state model.
Upvotes: 0
Reputation: 1538
Nice example. Looks terse to me. A little hint to start typing with 'j', 'b' or 'm' would avoid the need to read all the code or assume the example is broken ;)
For a hub and spoke getter/setter arrangement like a dashboard and subviews, the observer pattern just adds additional overhead without any decoupling benefits since the dashboard must initiate the subviews anyways.
It would make more sense if the 'project' subview would observe the 'user' subview. This would allow for complex and reusable logic between the subviews with a light dashboard limited to the initiation.
Upvotes: 1