user4398654
user4398654

Reputation: 1

Mithril js - cross component communication pattern

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:

  1. If you had to pick between these two implementation, why would you pick one over the other?
  2. In the functional programming model, is an OOP concept such as the observer pattern frowned upon?
  3. Is there a more terse but scalable way to implement this in either FP / using a different pattern?

Upvotes: 0

Views: 1234

Answers (2)

Daniel
Daniel

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

Hurelu
Hurelu

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

Related Questions