通过端口将多个参数传递给Javascript

时间:2016-08-28 09:53:45

标签: elm

我需要将一些参数传递给Javascript,但由于一个奇怪的原因,它无法编译。我开始时:

port check : String -> Cmd msg

这很好(直接来自JavaScript Interop)。但是当我添加另一个参数时

port check : Int -> String -> Cmd msg

我正在

  

1 |端口检查:Int - >字符串 - > Cmd msg
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

     

你说它应该是:

Int -> String -> Platform.Cmd.Cmd msg
     

但您需要使用此处描述的特定格式:   http://guide.elm-lang.org/effect_managers/

我只是通过将参数减少回一个

来解决这个问题
type alias Bundle = (Int, String)
port check : Bundle -> Cmd msg

但如果我可以做到那就更清洁

app.ports.check.subscribe(function(arg1, arg2) {
});

为什么它不编译?

2 个答案:

答案 0 :(得分:13)

port只能有一个参数。如果您需要传递多个参数,那么您唯一的选择就是传递一个元组(就像您使用Bundle所做的那样)或记录。

在js方面,你将不得不采用一个参数,但你可以用你想要的任何var名称对其进行解构

app.ports.check.subscribe(function(arg) {
  var [arg1, arg2] = arg;
});

如果您正在使用ES6,那么如果您使用记录like this,那么您在函数参数中确实有一些更好的解构选项:

app.ports.check.subscribe(function({arg1: arg1, arg2: arg2}) {
});

答案 1 :(得分:7)

我注意到你不必在Javascript方面“解码”很多。因此,您可以将单个参数打包为ELM中的一个好类型。

在榆树上做这样的事情:

type alias MyObject = 
  { name: String 
  , displayDate: String
  , subTitle: String
  , hashTag: String
  }

port check : MyObject -> Cmd msg 

然后在javascript中你可以这样做:

app.ports.check.subscribe(function(myObject) {
            alert( myObject.name);
            alert( myObject.displayDate);
            alert( myObject.subTitle);
            alert( myObject.hashTag);
        });
相关问题