Fay JQuery work with array of elements

2019-05-13 21:38发布

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?

标签: jquery fay
1条回答
女痞
2楼-- · 2019-05-13 22:17

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.

查看更多
登录 后发表回答