Suppose you want to create a UI which has 3 buttons. When you click in one of them, the others are released. In JavaScript, you could write:
var elements = ["Foo","Bar","Tot"].map(function(name){
var element = document.getElementById(name);
element.onclick = function(){
elements.map(function(element){
element.className = 'button';
});
element.className = 'button selected';
};
return element;
});
.button {
border: 1px solid black;
cursor: pointer;
margin: 4px;
padding: 4px;
}
.selected {
background-color: #DDDDDD;
}
<div>
<span id='Foo' class='button'>Foo</span>
<span id='Bar' class='button'>Bar</span>
<span id='Tot' class='button'>Tot</span>
</div>
That is stateful, but not modular, self contained nor pure. In fact, it is so bad the state (a ternary bit) isn't even obvious. You can not inject it inside another model, how many times you want.
Most of the answers provided here so far are stateful, but not modular. The issue is that using that strategy, you can't drop a component inside another without the parent knowing about the children's model. Ideally, that would be abstracted away - the parent shouldn't need to mention the model of the child nodes on its own model, nor manually plumbing state from parent to node should be necessary. If I want to create a list of the app above, I don't want to store the state of each child node on the parent.
How do you create stateful, modular, self-contained web components in Elm?