我认为它将附带的代码编译成Javascript,但代码是如何编译而不是执行的?例如,此代码来自 Simply Lift :
object AjaxExample {
def render = {
// state
var name = ""
var age = "0"
val whence = S.referer openOr "/"
// our process method returns a
// JsCmd which will be sent back to the browser
// as part of the response
def process(): JsCmd= {
// sleep for 400 millis to allow the user to
// see the spinning icon
Thread.sleep(400)
// do the matching
asInt(age) match {
// display an error and otherwise do nothing
case Full(a) if a < 13 => S.error("age", "Too young!"); Noop
// redirect to the page that the user came from
// and display notices on that page
case Full(a) => {
RedirectTo(whence, () => {
S.notice("Name: "+name)
S.notice("Age: "+a)
})
}
// more errors
case _ => S.error("age", "Age doesn't parse as a number"); Noop
}
}
// binding looks normal
"name=name" #> SHtml.text(name, name = _, "id" -> "the_name") &
"name=age" #> (SHtml.text(age, age = _) ++ SHtml.hidden(process))
}
}
答案 0 :(得分:5)
JsCmd不编译或执行任何操作。相反,它是一种更加类型安全的构造Javascript字符串的形式,可以发送到浏览器,在那里它们可能被执行。
答案 1 :(得分:1)
对于任何将由ajax调用的此类过程方法,方法中的Scala代码可以分为两部分:
将转换为javascript的唯一代码是从方法返回的代码,正如您从方法签名中看到的,它是Lift JsCmd对象。在此特定示例中,process方法的返回值是各种case语句的返回值。第一个case语句调用S.error,第二个调用S.notice,第三个调用S.error。这些将被转换为javascript以发送回浏览器。如果你想看到实际的javascript,它会被Lift记录下来。例如如果我有一个带有“title”属性的表单,并且我通过调用S.error(“title”,“错误的标题”)报告错误,那么我的日志显示:
13:32:32.841 [291876857@qtp-349619216-4] DEBUG comet_trace - AJAX Response:
8b5ruvtezi521nbful5n7s3cp
InMemoryResponse(try{jQuery("#lift__noticesContainer__").each(function(i)
{this.innerHTML = "<div id=\"lift__noticesContainer___error\"><ul>
<li>wrong title</li>
</ul></div>";});} catch (e) {}
try{jQuery("#title").each(function(i) {
this.innerHTML = "<span id=\"title\">wrong title</span>";});}
catch (e) {},
List((Content-Length,295), (Content-Type,text/javascript; charset=utf-8)),
List(), 200)
如果你想看一些使用JsCmd的例子,我建议“探索电梯”:
http://exploring.liftweb.net/master/index-11.html
顺便说一下,对于Lift问题我建议询问Lift google组而不是Stack Overflow。这是官方支持渠道,社区反应迅速。