簡體   English   中英

Purescript 中的 getElementById

[英]getElementById in Purescript

我對 Purescript 很陌生,所以這可能是一個幼稚的問題。

I want to write a Purescript function that reads input from HTML input elements on the browser and writes some output to another HTML input element.

使用普通的 Javascript 就像document.getElementById('output').value = myFun(document.getElementById('input')); . 我如何只用 Purescript 做到這一點?

編輯:

我注意到我的答案不符合要求 - 我只是設置一個元素值。 如果我找到更多時間,我可能還會添加從元素值中讀取的內容,但是您應該能夠從已經提供的提示中猜出如何做到這一點:-)


一般來說,在使用 PureScript 時,您希望使用一些高級框架來操作 DOM,例如:halogen、react-basic、concur、spork、elmish、flare、hedwig、flame(當然我錯過了其他一些 - 抱歉) .

但是,如果您真的想手動修改 DOM,請不要感到驚訝,因為它不像命令式 JavaScript 那樣令人愉快。 這是有目的的——PureScript 有能力將效果與純函數分開,我們必須在每一步都使用Effect 另一方面,這給了我們一種獨特的能力來推理代碼並確定副作用可能發生在哪里以及我們程序的哪些部分是純的。

所以讓我們使用低級別的purescript-web-html 這個庫是低級的,但是圍繞 DOM API 提供了嚴格的類型,所以就像我說的那樣,它需要大量的手動值傳遞:

module Main where

import Prelude

import Data.Maybe (Maybe(..))
import Effect (Effect)
import Web.DOM.Document (toNonElementParentNode)
import Web.DOM.Element (setAttribute)
import Web.DOM.NonElementParentNode (getElementById)
import Web.HTML (window)
import Web.HTML.HTMLDocument (toDocument)
import Web.HTML.Window (document)

main :: Effect Unit
main = do
  w ← window
  d ← document w
  maybeElement ← getElementById "test-input" $ toNonElementParentNode $ toDocument  d
  case maybeElement of
    Nothing → pure unit
    Just elem → do
      setAttribute "value" "new-value" elem

這可以使用無點樣式寫得更短一些,從而避免中間變量:

main :: Effect Unit
main = window >>= document >>= toDocument >>> toNonElementParentNode >>> getElementById "test-input" >>= case _ of
  Nothing → pure unit
  Just elem → setAttribute "value" "new-value" elem

直接 DOM 操作可能不是開始構建更大的項目或使用這種非常棒的語言開始冒險的最佳方式。 另一方面,它有時會很有用;-)

我使用 Purescript 的 Foreign Function Interface (FFI) 功能如下。

使用您要使用的外部函數的導入來定義您的 Purescript 模塊。 這里我們導入了兩個函數。

-- Main.purs
foreign import getElementById :: String -> Effect String
foreign import setElementById :: String -> String -> Effect Unit 

現在創建一個具有相同名稱但擴展名為.js的 Javascript 文件。 我們將從這里導出 JS 函數以在 Purescript 中使用。

// Main.js
"use strict";

exports.getElementById = function(id) {
    return document.getElementById(id).value;
};

exports.setElementById = function(id) {
    return function(value) {
    document.getElementById(id).value = value;
    };
};

現在我們可以在 Purescript 文件中調用getElementByIdsetElementById函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM