bjenkins001
bjenkins001

Reputation: 141

How to invoke 3rd party javascript from scala-js?

I need help initializing a native JS var from within a scalajs app (specifically a scalajs-react app). Fundamentally, I'm trying to use Bootstrap Responsive data-tables and I need to initialize a data table by getting the element of the data table in my HTML via a call to dom.getElementById which will be of type DataTable and then I need to initialize like this:

$(document).ready(function() {
    $('#example').DataTable();
} );

I've been staring at the @js.native stuff and can't quite figure out how to make the connection to that native JS. Any help would be greatly appreciated. For reference, the link to the native javascript of the responsive data-table is here. An additional question for those with a scalajs-react background (are you there @japgolly?) is whether or not the best place to make this data-table initialization invocation should be in the ReactComponentB.componentDidMount() method?

Upvotes: 0

Views: 536

Answers (1)

gzm0
gzm0

Reputation: 14842

The simplest way to set up the data table is by doing so using the dynamic API:

dom.document.getElementById("example").asInstanceOf[js.Dynamic].DataTable()

Of course you need to do so only once the document is loaded. You can use scala-js-jquery to do so:

jQuery(dom.document).ready(() =>
  dom.document.getElementById("example").asInstanceOf[js.Dynamic].DataTable()
)

If you would like to have a nicer (and typesafe) invocation of DataTable, you can follow the Monkey Patching Guide (sorry no anchor, search for the term):

@js.native
trait DataTableElement extends dom.Element {
  def DataTable(): Unit = js.native
}

object DataTableElement {
  implicit def element2dataTableElement(e: dom.Element): DataTableElement =
  {
    e.asInstanceOf[DataTableElement]
  }
}

You now won't need the cast anymore:

dom.document.getElementById("example").DataTable()

And:

jQuery(dom.document).ready(() =>
  dom.document.getElementById("example").DataTable()
)

Upvotes: 2

Related Questions