【问题标题】:What is the equivalent for new after require in ScalaJS?ScalaJS 中的新需求后的等价物是什么?
【发布时间】:2016-02-19 21:46:01
【问题描述】:

我看到here

javascript:

var D3Funnel = require('d3-funnel');
var chart = new D3Funnel('#funnel');

我设法让第一行在ScalaJS 中使用:

ScalaJS:

val Funnel = js.Dynamic.global.require("d3-funnel")

但是 ScalaJS 中的第二行 var chart = new D3Funnel('#funnel'); 应该是什么?

【问题讨论】:

    标签: scala.js


    【解决方案1】:

    目前有点难看。要创建动态类的实例,必须使用js.Dynamic.newInstance

    import scala.scalajs.js
    
    val chart = js.Dynamic.newInstance(Funnel)("#funnel")
    

    从那里,我建议将 chart 转换为静态定义的 API:

    @js.native
    trait Funnel extends js.Object {
      def someMethodOfFunnel(): Unit = js.native
    }
    
    val chart = js.Dynamic.newInstance(Funnel)("#funnel").asInstanceOf[Funnel]
    chart.someMethodOfFunnel() // statically typed
    

    【讨论】:

    • 我在 ScalaJS 文档中读到 Native JS types should be annotated with @js.native for forward source compatibility with Scala.js 1.0.0. 我看到你在这里使用了 @js.native 但我不明白为什么 Funnel 不是原生 JS 类型所以我们为什么要使用 @987654330 @?
    • 是的,因为它是在 d3-funnel 库中实现的,它是用原生 JavaScript 编写的。
    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2014-06-12
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多