How to translate a JQuery function value in Javascript to ScalaJS (scalajs-jquery)

柔情痞子 提交于 2019-12-11 13:45:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!