arguments.callee in scala.js -
i porting javascript function scala.js:
once: function (el, type, callback) { var typearray = type.split(' '); (var = typearray.length - 1; >= 0; i--) { el.addeventlistener(typearray[i], function(e) { e.target.removeeventlistener(e.type, arguments.callee); return callback(e); }); }; },
here attempt @ writing scala code:
def once(element: topnode, tpe: string, callback: function1[event,any]): unit = { tpe.split(" ").foreach(item => element.addeventlistener(item, (e : event) => { e.target.removeeventlistener(e.`type`, ?) // <-- put here? callback(e) })) }
how can reference lambda in place holder?
scala.js not have equivalent of arguments.callee
of javascript. more generally, not have equivalent of arguments
. lambda cannot read reference itself, unless given via captured environment. can achieved storing lambda in val
in once
method. ideally, 1 write this:
def once(element: topnode, tpe: string, callback: function1[event,any]): unit = { val cb: js.function1[event, any] = { (e: event) => e.target.removeeventlistener(e.`type`, cb) // using cb here callback(e) } tpe.split(" ").foreach(item => element.addeventlistener(item, cb)) }
however, won't compile, because cannot use val (here cb
) in right-hand-side of definition, if happens inside lambda. trying results in following compile error:
main.scala:17: error: forward reference extends on definition of value cb e.target.removeeventlistener(e.`type`, cb) // using cb here
there simple solution, though: use lazy val
instead:
def once(element: topnode, tpe: string, callback: function1[event,any]): unit = { lazy val cb: js.function1[event, any] = { (e: event) => e.target.removeeventlistener(e.`type`, cb) // using cb here callback(e) } tpe.split(" ").foreach(item => element.addeventlistener(item, cb)) }
make sure declare cb
js.function1
, not function1
. otherwise cb
refer scala function, not js function resulting automatic conversion (which have different identities). have make sure cb
refers js function.
fiddle: http://www.scala-js-fiddle.com/gist/2b848e2f01e7af522dc1
Comments
Post a Comment