Skip to content

Commit

Permalink
Add withElement and updateAttr functions to the DOM library.
Browse files Browse the repository at this point in the history
See the comments for each function in lib/dom.ls for details.
  • Loading branch information
valderman committed Jun 15, 2011
1 parent cfbfb43 commit 20b7481
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
17 changes: 4 additions & 13 deletions examples/scroller/scroller.ls
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,9 @@ import io;
import std;
import dom;

update :: DOMElement -> Int -> IO ();
update e t = do {
txt <- getAttr e "innerHTML";
setAttr e "innerHTML" (tail txt ++ [head txt]);
setTimeout (update e t) t;
update t e = do {
updateAttr e "innerHTML" (\txt -> tail txt ++ [head txt]);
setTimeout (update t e) t;
};

scroll :: String -> Int -> IO ();
scroll id t = do {
elem <- getElementById id;
case elem of
(Just e) -> update e t;
_ -> error ("No such element: " ++ id);
;
};
scroll id t = withElement id (update t);
22 changes: 21 additions & 1 deletion lib/dom.ls
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
-- This is basically a wrapper for the more useful DOM manipulation functions.
export getElementById, parentNode, getAttr, setAttr, firstChild, lastChild,
nextSibling, prevSibling, childNodes, siblings, domElemValid,
DOMElement;
DOMElement, withElement, updateAttr;
import io;
import std;

Expand All @@ -19,6 +19,17 @@ getElementById id = do {
if valid then return (Just x) else return Nothing;
};

-- Performs an IO action using the element with the given ID.
-- If the element doesn't exist, Nothing is returned.
withElement :: String -> (DOMElement -> IO a) -> IO (Maybe a);
withElement id m = do {
e <- getElementById id;
case e of
(Just e) -> do {x <- m e; return (Just x);};
_ -> return Nothing;
;
};
-- Reads any DOM node text attribute.
getAttr :: DOMElement -> String -> IO String;
getAttr e attr = _jsfun "(function(e,s) {return e[s];})" 2 e attr;
Expand All @@ -30,6 +41,15 @@ setAttr e attr s = do {
return ();
};
-- Applies the given function to the value of the given attribute of the given
-- element and updates that attribute with the result. If the element doesn't
-- exist, the function does nothing.
updateAttr :: DOMElement -> String -> (String -> String) -> IO ();
updateAttr e a f = do {
s <- getAttr e a;
setAttr e a (f s);
};

-- Wrapper for <element>.parentNode
parentNode :: DOMElement -> IO DOMElement;
parentNode e = do {
Expand Down

0 comments on commit 20b7481

Please sign in to comment.