I am attempting to learn purescript
.
I have a button in some HTML that I am trying to print the class name of. I am building and browserifying
using pulp
.
The function I am using is querySelector:
import Web.DOM.ParentNode (querySelector)
This returns the item I want, Element, within two "boxes": an outer Effect monad and an embedded Maybe monad:
> :type querySelector
QuerySelector -> ParentNode -> Effect (Maybe Element)
My Effect monad looks like:
getBtn :: Effect Unit
getBtn = do
doc <- map toParentNode (window >>= document)
button <- querySelector (wrap "#btn") doc
... Need to extract class name from 'button' here
I know I can get to the inner Maybe by calling bind (>>=) on the outer Effect monad. My first plan of attack was to unbox the Maybe manually using the maybe funtion. Here's how you do this for a simple Int:
> maybe 0 (\x -> x) $ Just 7
7
for a Maybe Element I think it would look something like:
unboxMaybeElement :: Maybe Element -> Element
unboxMaybeElement Nothing = Nothing
unboxMaybeElement (Just a) = maybe (Element ..note: trying to create a default element here) (\x -> x) a
One problem is I cannot find a constructor for type Element, so I am unable to supply a default value (the first arg of maybe), so I can't use this method.
In addition, I can't find a definition for the Element type.
I also read that it's not a good idea to reach inside a Maybe anyway, but instead to lift the functions going against it by using a functor (like map or fmap
).
In this vein I tried to call an external function like:
button <- querySelector (wrap "#btn") doc
let cn = getClassName button
log $ "classname=" <> show cn
-- The basic question is how to implement this function?
getClassName :: Maybe HTMLElement -> String
getClassName e = map className (map fromElement e)
Note: className and fromElement are supplied in Web.HTML.HTMLElement.
As you can see, I'm trying to promote up the functions by calling them with a map, because the functions do not deal with Maybes, but I'm getting stuck in a morass of type conflicts between "Maybe Element" and "Element" and "HTMLElement" vs "Element" etc.
Yes, I admit I have a couple of issues going on here, and this isn't really a beginners problem, but it just irks me that something so simple as obtaining the class name of an HTML object is so hard. Surely, I must be missing something?
BTW, Here is my html:
<!doctype html>
<html>
<body>
<script src="index.js"></script>
<p>
<input type="button" class="btn-class" value="click me" id="btn"/>
</p>
</body>
</html>
The more general question is: how do you get to values nested two monad levels deep?