Search code examples
scalaliftlift-json

In Lift, making a JObject with an inline function


It's common in JavaScript, particularly in jQuery, to have a function call with a literal argument and for a field of that argument to be an inline anonymous function. Like this:

$(function () {
    $("#mylist").sortable({
        placeholder: "ui-state-highlight",
        stop: function () { alert('Hello!'); }
    });
});

Is it possible to make such a call from Lift? This is as far as I've gotten:

"#jsonScript" #> Script(js.jquery.JqJsCmds.JqOnLoad(
    js.jquery.JqJE.Jq("#mylist") ~> js.JE.JsFunc("sortable", JObject(
        JField("placeholder", JString("ui-state-highlight")) ::
        JField("stop", js.JE.AnonFunc(js.JsCmds.Alert("Hello!"))) ::
        Nil
    ))
))

The compiler complains that AnonFunc is not a JValue, which is absolutely true: it's not. But in JavaScript a function () {} call is a legal value for a literal object field. How can I let Lift know that?

The long-term goal here is for the function body to eventually be a:

SHtml.jsonCall( JE.Call("jsFunction"), liftFunction _ )

Solution

  • I needed to use JsObj:

    def render = 
        "#jsonScript *" #> js.jquery.JqJsCmds.JqOnLoad(
            js.jquery.JqJE.Jq("#mylist") ~> js.JE.JsFunc("sortable", js.JE.JsObj(
                ("placeholder", "ui-state-highlight"),
                ("stop", js.JE.AnonFunc(SHtml.jsonCall( JE.Call("jsFunction"), liftFunction _)))
            ))
        ).cmd