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 parameters, e.g.
jQuery.ajax({
url: "http://www.example.com/foo",
success: function() {
..
}
})
The current documentation for Scala.JS recommands using a Scala trait to represent the options object, but that leads to a problem when you have to create the options since you cannot pass an anonymous class into JavaScript code.
How can such option objects be created from Scala code?
Here's a method that I've found to work quite well:
Of course this assumes that the FooOptions trait has declared the fields as var. If not, you'll have to use
but that is less type-safe.
If you're declaring your own options trait, you could also add a companion object with an appropriate apply method:
That'll make calling code a lot prettier:
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:
That
UndefOr[T]
means "this field might containT
, or might beundefined
"; note that you are initializing those tojs.undefined
, so they have a default value.Then, at the call site, you simply override the values that you need to set:
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 assuccess
above) get left asundefined
, 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.
We recommend the following (if you chose to create facade-types):
The advantage is that the type-unsafe cast is contained in a single location. Further, if you ever decide to add/remove fields to/from
AjaxOptions
, you will (hopefully) think of also adapting the companion'sapply
method. As a result, the typer will inform you where you have to change your invocations (rather than just having the new field set toundefined
).Please refer to What is the suggested way to instantiate a js.Object for API wrappers for more.