Skip to content

Instantly share code, notes, and snippets.

@yangbajing
Last active December 14, 2015 01:59
Show Gist options
  • Save yangbajing/5010405 to your computer and use it in GitHub Desktop.
Save yangbajing/5010405 to your computer and use it in GitHub Desktop.
在liftweb 中扩展一个类似 jQuery的方法:$("...").XXX() 和 jQuery("...").XXX()。
package yangbajing.util.web
import scala.xml.{ NodeSeq, Text, Elem }
import net.liftweb.http.js.{ JsExp, JE, JsMember, JsCmd, JsCmds }
import net.liftweb.http.js.jquery.{ JqJE, JqJsCmds }
import net.liftweb.util.StringHelpers._
object jQuery {
def apply(exp: String): jQuery = apply(JE.Str(exp))
def apply(exp: JsExp): jQuery = new jQuery(exp)
}
class jQuery(exp: JsExp) {
val jq = JqJE.Jq(exp)
def html(content: NodeSeq) =
(jq ~> JqJE.JqHtml(content)).cmd
def html() =
(jq ~> JqJE.JqHtml()).cmd
def append(content: NodeSeq) =
(jq ~> JqJE.JqAppend(content)).cmd
def appendTo(content: NodeSeq) =
(jq ~> JqJE.JqAppendTo(content)).cmd
def prepared(content: NodeSeq) =
(jq ~> JqJE.JqPrepend(content)).cmd
def preparedTo(content: NodeSeq) =
(jq ~> JqJE.JqPrependTo(content)).cmd
def value(value: JsExp) =
(jq ~> SetValue(value)).cmd
def value() =
(jq ~> Value()).cmd
def attr(key: String) =
(jq ~> JqJE.JqGetAttr(key)).cmd
def attr(key: String, value: JsExp) =
(jq ~> JqJE.JqAttr(key, value)).cmd
def removeAttr(key: String) =
(jq ~> RemoveAttr(key)).cmd
def getClass(key: String) =
(jq ~> JqJE.JqGetAttr(key)).cmd
def setClass(value: JsExp) =
attr("class", value)
def remove() =
(jq ~> JqJE.JqRemove()).cmd
private case class RemoveAttr(key: String) extends JsExp with JsMember {
def toJsCmd = "removeAttr(" + key.encJs + ")"
}
private case class SetValue(value: JsExp) extends JsExp with JsMember {
def toJsCmd = "val(" + value.toJsCmd + ")"
}
private case class Value() extends JsExp with JsMember {
def toJsCmd = "val()"
}
}
@kevin4936
Copy link

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment