0

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?

1 Answer 1

2

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()
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.