A question about events and messages

Consider this code.

https://runelm.io/c/s6k

It contains two svg shapes. Each has an onClick that triggers a message. The goal is to let the update function react differently to clicks on different objects, hence type Message has two constructors instead of one.

This doesn’t scale well. To handle twenty differnt objects I would need twenty message constructors and twenty cases in the upate function. How should I handle this instead?

So far, what I have come up with, is this.

https://runelm.io/c/y2z

The list of shapes gets explicitely indexed via indexedMap and the Click message constructor becomes a Click Int. It does what I want, but it seems somewhat DIY to me. Is there a standard approach to this sort of thing, that I should use instead?

Good question. It kind of depends on what you need in a particular case, doesn’t it? In some cases you have a small, fixed number of things that can be clicked. In other cases you have an arbitrary number of things, perhaps created by the user, that can be clicked. And you have gradations between these two poles. Using Click Int seems awkward and overkill to model the first kind of case.

But if you’re just asking about the second kind of case, dealing with clicks from an arbitrary number of shapes, it depends on how you are modelling your collection of shapes. In a lot of cases List Shape will do, but depending on what the UI is you may have Array Shape or Dict Id Shape or Tree Shape or Zipper Shape, etc. , and this would guide you how structure your Click to index into them.

At least, that’s the way I would think about it. The UI/UX guides your decisions about data structures and how they are updated with Msg types. There’s not a one size fits all approach. That said, your List Shape/Click Int approach is very very common I’d say for basic use cases.

2 Likes

That makes sense. Thanks for your reply!

The idea of using only one message makes a lot of sense, but prefer using something different than the index if possible e.g. you could add an id or code field to each shape. Really depends on what you are going to do with that information in update. If you use the index you might end up coupling your update code to specific positions in the list, making it hard to change.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.