问题
I need to implement a call from scala.js a method like:
sigma.classes.graph.addMethod('getNodesCount', function() {
return this.nodesArray.length;
});
that is the way that bring the library in JS to access the internal array nodesArray of the class sigma.clasess.graph. I tried something like
trait GraphClassesJS extends js.Object {
def addMethod(name:String,handler: js.Function0[Any]):Unit=js.native
}
I try to call with
s.classes.graph.addMethod("getNodesCount",()=>js.ThisFunction.nodesArray.length)
but I get
value nodesArray is not a member of object scala.scalajs.js.ThisFunction
[error] s.classes.graph.addMethod("getNodesCount",()=>js.ThisFunction.nodesArray.length)
How can I do it? Thanks Reynaldo
回答1:
You misunderstood the nature of js.ThisFunction
. It is not a syntactical replacement for this
from JS. It is an alternative hierarchy of types for functions that take this
as an explicit parameter.
The definition you need is almost what you wrote, but replacing js.Function0
by js.ThisFunction0
, and specifying the type of Thing
which contains the field nodesArray
(maybe Graph
?):
trait Thing extends js.Object {
def nodesArray: js.Array[Node]
}
trait GraphClassesJS extends js.Object {
def addMethod(name: String, handler: js.ThisFunction0[Thing, Any]): Unit = js.native
}
Now, you can call it like this:
s.classes.graph.addMethod("getNodesCount", thiz => thiz.nodesArray.length)
Now thiz
is the exact equivalent of the JS this
. Its type is inferred to be Thing
.
来源:https://stackoverflow.com/questions/29951782/access-the-js-this-from-scala-js