You sometimes want to “ignore” an event based on application state. For example, let’s say that clicking on a user’s profile picture takes you to their profile. But if a user has left the platform, you might want their posts to keep existing with their profile picture, but nothing should happen when you click on their portrait picture.
A common pattern to handle this in Elm applications (according to a quick search with grep.app) is by using a “dummy” NoOp message which, when handled in update, just returns the Model. In the HTML attribute, you write code that looks like this:
if someCheckPassed then
onClick DoSomething
else
onClick NoOp
Both branches have to generate the same type, so you can’t leave one of the blank. The downside is that this clutters up your Msg type, is (minor) noise in your update function, and is also noise in the debugger.
So I thought, why not just ignore it at the source? One can write:
if someCheckPassed then
onClick DoSomething
else
on “dummy” (Json.Decode.fail “nope”)
Now that event just gets silently discarded at the source; the update shouldn’t even trigger for it. No extra message, no debugging noise. It might even be cheaper than a NoOp message, unless I’m missing a trick. You can also encode this logic into a tiny function so that one can write
someCheckPassed |> thenPermitInteraction (onClick DoSomething)
(Another way around is to supply some non-event Attribute in the else branch instead of an always-failing event, but that might add noise to the HTML.)
I’m probably not the first to think of this approach. It seems like a cleaner solution than NoOp messages. Is there some drawback to it that I’m not seeing?