Fay JQuery work with array of elements

ぃ、小莉子 提交于 2019-12-22 10:44:02

问题


What is the preferred way, how to compute the number of elements selected by a selector?

One way I can think of, is to call JQuery's size:

size :: JQuery -> Fay Int
size = ffi "%1['size']()"

The other way is to get a list from a function call and then count the elements. The type of the function, that retrieves the elements would probably be:

elems :: JQuery -> Fay [Elem]

Anyone know, how to implement it? How does one describe the mapping between javascript types and haskell types?


回答1:


There are two ways to handle javascript objects in Fay.

Opaque data types

Using EmptyDataDecls:

{-# LANGUAGE EmptyDataDecls #-}
[...]
data JQuery

This is what fay-jquery does, it allows users of the library to define new FFI bindings easily, so your size example works. But note that it has been deprecated in jQuery, so it's better to use length as John B suggests.

Whenever fay encounters something that should be of type JQuery it won't touch it so you will have a direct reference to the javascript object.

Records

The other approach is to map a javascript object to a record, this is the nicer option if the object in question maps easily, such as when handling JSON or doing client-server communication.

data User = User { name :: String }

userA :: User
userA = ffi "{ instance : \"User\", name : \"Adam\" }"

userB :: User
userB = User { name = "Adam" }

These are identical ways of constructing a User record, but userA is of course a little contrived, probably the value would be fetched from the server side or from some JS library in that case (otherwise there is no reason to use the FFI at all)

In this record case you will not keep a reference to a JS object, an immutable User record will be instantiated.

I also think you can skip Fay in the return type. I think it's safe to assume that the jQuery objects won't mutate, especially if they are instantiated from Fay.

length :: JQuery -> Int
length = ffi "%1['length']"

Also see the FFI wiki page.

Edit: Slightly related, fay-uri is a well documented and fairly simple example of how to build an immutable FFI layer on top of a mutable js library.



来源:https://stackoverflow.com/questions/16196595/fay-jquery-work-with-array-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!