2010/10/29 4 Comments
o.f) and using an object as an array using brackets (like
data Document foreign import jscript "document" document :: IO Document foreign import jscript "%1.write()" documentWrite :: Document -> JSString -> IO () foreign import jscript alert :: JSString -> IO ()From within a browser the document representation can be accessed via the global variable
document, the foreign entity
"%1.write()"specifies that from all arguments the first one is used as the receiver of the method write. The parenthesis
()specify that a call has to be made, passing all arguments except those referred to explicitly by means of
<nr> >= 1refers to argument <nr>. If an entity is omitted as in alert it defaults to
<functionname>is the name of the foreign function being defined. Function documentWrite does not accept a String but a JSString instead, defined to be the platform dependent representation of Strings, converted to and from String with corresponding conversion functions.
main = alert $ stringToJSString "Hi there!"As this would pop up an alert box, an alternative Hi is the following program which writes to the document instead:
main = do d <- document documentWrite d $ stringToJSString "Hi there!"Actually, the usual Hello would have worked as well because it is implemented as writing to the document:
main = putStr "Hi there!"To show the usefulness of array like access as part of we do a bit of rudimentary DOM programming:
main = do d <- document nl <- documentGetElementsByName d (stringToJSString "myHeader") print (nodeListLength nl) n <- nodeListItem nl 0 print $ jsStringToString $ elementTagName n print $ jsStringToString $ elementInnerHTML nGiven the presence of
with the name "myHeader" in the document where the program is run, it will produce the following as part of the document:
Head says hello!
1 "H1" "Head says hello!"