Fay JQuery使用元素数组 [英] Fay JQuery work with array of elements

查看:102
本文介绍了Fay JQuery使用元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首选方法是什么,如何计算选择器选择的元素数量?

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

我能想到的一种方法是调用JQuery的size:

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]

任何人都知道,如何实施?如何描述javascript类型和haskell类型之间的映射?

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

推荐答案

在Fay中有两种处理javascript对象的方法.

There are two ways to handle javascript objects in Fay.

使用EmptyDataDecls:

Using EmptyDataDecls:

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

这是fay-jquery的工作,它允许库的用户轻松定义新的FFI绑定,因此您的大小示例有效.但是请注意,它已在jQuery中弃用,因此最好像John B所建议的那样使用length.

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.

每当fay遇到应该是JQuery类型的东西时,它都不会碰到它,因此您将直接引用javascript对象.

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.

另一种方法是将javascript对象映射到记录,如果有问题的对象易于映射(例如在处理JSON或进行客户端-服务器通信时),则这是一个更好的选择.

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" }

这些是构造用户记录的相同方法,但是userA当然有些人为设计,在这种情况下,可能会从服务器端或某些JS库中获取值(否则,没有理由使用FFI完全)

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)

在这种情况下,您将不会保留对JS对象的引用,将实例化不可变的User记录.

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

我还认为您可以在返回类型中跳过Fay.我认为可以肯定地认为jQuery对象不会发生突变,特别是如果它们是从Fay实例化的.

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']"

另请参见 FFI Wiki页面.

略有相关的 fay-uri 有据可查,并且一个非常简单的示例,说明如何在可变的js库之上构建不可变的FFI层.

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.

这篇关于Fay JQuery使用元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆