问题
In my ScalaJS project I use Semantic-UI with scala-js-jquery
I use this to monkey patch JQuery:
// Monkey patching JQuery
@js.native
trait SemanticJQuery extends JQuery {
def dropdown(params: js.Any*): SemanticJQuery = js.native
def popup(params: js.Any*): SemanticJQuery = js.native
// and more
}
// Monkey patching JQuery with implicit conversion
implicit def jq2semantic(jq: JQuery): SemanticJQuery = jq.asInstanceOf[SemanticJQuery]
For example $('select.dropdown').dropdown();
translates to jQuery(".ui.dropdown").dropdown(js.Dynamic.literal(on = "hover"))
.
My problem now is how to translate this:
// custom form validation rule
$.fn.form.settings.rules.adminLevel = function(value, adminLevel) {
return (window.user.adminLevel >= adminLevel)
};
回答1:
Your JS snippet
// custom form validation rule
$.fn.form.settings.rules.adminLevel = function(value, adminLevel) {
return (window.user.adminLevel >= adminLevel)
};
straightforwardly translates to
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
// custom form validation rule
g.$.fn.form.settings.rules.adminLevel = { (value: js.Dynamic, adminLevel: js.Dynamic) =>
g.window.user.adminLevel <= adminLevel
}
You could do something nicer with static types if you have some to represent those structures, but that's basically it if you're satisfied with a dynamically typed solution.
来源:https://stackoverflow.com/questions/49649799/how-to-translate-a-jquery-function-value-in-javascript-to-scalajs-scalajs-jquer