How do I create “options objects” in Scala.Js?

前端 未结 3 472
礼貌的吻别
礼貌的吻别 2020-12-10 05:31

In idiomatic JavaScript it\'s common to have a function accept an \"options object\" as the last parameter. This is where you\'d usually put all the option/seldom-used param

3条回答
  •  离开以前
    2020-12-10 05:51

    Since Scala.js has evolved, I'm amending my answer with the current best practice:

    At this point, you should use a trait to describe the options object, like this:

    trait AjaxOptions extends js.Object {
      var url: String
      var success: UndefOr[js.Function0[Unit]] = js.undefined
    }
    

    That UndefOr[T] means "this field might contain T, or might be undefined"; note that you are initializing those to js.undefined, so they have a default value.

    Then, at the call site, you simply override the values that you need to set:

    val ajaxResult = new AjaxOptions {
      url = "http://www.example.com/foo"
    }
    

    Note the curly braces: you're actually creating an anonymous subclass of AjaxOptions here, that does what you want. Any fields you don't override (such as success above) get left as undefined, so the library will use its default.

    Old Answer:

    This question is pretty old, but since people are still coming here:

    If you have a large and complex options object (as is typical of, say, jQuery UI classes), you may want to build a facade for that using JSOptionBuilder, which is found in the jsext library. JSOptionBuilder isn't quite a panacea, but it's a not-too-much boilerplate mechanism for constructing and using arbitrarily complex options objects.

提交回复
热议问题