In Lift, making a JObject with an inline function - scala

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 _ )

Here is an answer I gave a while back to someone who wanted to integrate Lift with jquery autocomplete, which uses a similar callback method: Lift - Autocomplete with Ajax Submission

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

Related

Possible forms of function literals in Scala

I was looking at some Scala 2 code in a project I am working on that seemed very strange to me.
Suppose there is a method that takes a function as an argument like:-
def invoke(
request: Request,
block: (Request) => Future[Result]
)
The normal form of function literal that I am familiar with, would allow us to call invoke like this:
obj.invoke(
request,
(req: Request) => {
// a bunch of code
}
)
However, I am looking at some code where the sole argument is within the braces like:
obj.invoke(
request,
{
req: Request =>
// a bunch of code
}
)
Are the above two styles synonymous? If not then what is happening in the second way and when should it be used?
I am pretty new to Scala and have been reading from "Programming in Scala" but don't recall anything similar to the code I wrote above.

Where is the documentation to write an event handler for input text box?

Originally I wanted to know:
How do I write a handler for this?
type state = string;
type action = | ChangeName(string)
let reducer = (_state, action) => switch action { | ChangeName(text) => text }
[#react.component]
let make = () => {
let (state, dispatch) = React.usefReducer(reducer, "");
/* What is the parameter type and how do I decode it? */
let onChange = ??? => dispatch(ChangeText(????));
<input value=state onChange/>
}
Specifically, what is the parameter type for the punned onChange handler and how do I decode it?
Every reference I come across is for JS, which I'm having difficulty translating to Re.
EDIT
The answer I found by scraping github:
let onChange = event => dispatch(ChangeName(ReactEvent.Form.target(event)##value));
Say I'd like to use another JSX element, where's the documentation? OR, is their a supposition that people coming to this from elsewhere have knowledge apriori? (I'm mostly comfortable with 'c').
You can get the types of all the DOM attributes from https://github.com/rescript-lang/rescript-react/blob/v0.10.1/src/ReactDOM.res
This file contains bindings to ReScript-React's subset of DOM attributes. It has:
onChange: ReactEvent.Form.t => unit
ReactEvent.Form module is declared at https://github.com/rescript-lang/rescript-react/blob/v0.10.1/src/ReactEvent.resi#L168
When looking for anything specific to ReScript-React, search that repo.
Looks like you have the correct code to handle the event now. Btw, you have in some places the variant constructor ChangeName and in others ChangeText, I assume the correct one is one of those. The compiler will of course catch this too :-)

Lift: How to bind a Hyperlink to a serverside method

I am new to Lift, I want to use hyperlink instead of submit button. I am able to bind my submit button with a server-side method use CSS Selector. for example:
def render = {
// define some variables to put our values into
// process the form
def process() {
do something....
}
}
"type=submit" #> SHtml.onSubmitUnit(process)
}
I want to use hyperlink to submit my form instead of submit button. How can I bind hyperlink with process()(server-side) method.
Thanks,
Puneet
In this instance you would probably want to use SHtml.ajaxCall and supply the form information as the JsonContext (i.e. not bound with CSS selectors):
def ajaxCall (jsCalcValue: JsExp, jsContext: JsContext, func: (String) ⇒ JsCmd) : (String, JsExp)
Alternativly you could use SHtml.a:
def a (func: () ⇒ JsObj, jsonContext: JsonContext, body: NodeSeq, attrs: ElemAttr*) : Elem
Failing that you should look at the available methods in SHtml (jsonForm would be another one to look at) and see which one best fits your use case. I would encourage you to pick up a copy of Lift in Action which discusses how the function binding works, as I think you have miss-understood it in relation to the request/response cycle.

Scala: Generate a block that conditionally runs another block

In the Circumflex framework, you can map an URL to a block like this:
get("/foo") = {
"hello, world!"
}
which, when browsing to /foo, will show the given string as expected. Now, to write a complete web application, you almost always need some form of authentication and authorisation. I'm trying to write some kind of wrapper for the above construct, so I can write this:
get("/foo") = requireLogin {
"hello, world!"
}
The requireLogin method would then check if the user is logged in, and if yes, execute the given block. If not, however, it should do a redirect to the login page.
Now I somehow can't get the syntax right (i'm still a Scala newbie). How would you do this in a generic fashion?
Try something like this:
def executeMaybe[A](work: => A): Option[A] =
if (util.Random.nextBoolean)
Some(work)
else
None
This executes the passed code with probability 0.5, returning Some(<result delivered by work>), or returns None is the other cases. You can call it either like this:
val v = executeMaybe(42)
or with block notation:
val v = executeMaybe {
// do some work
// provide return value
}
The trick is to use a by-name parameter, signalled by the => symbol. Read more e.g. here: http://daily-scala.blogspot.com/2009/12/by-name-parameter-to-function.html
The way I asked it, Jean-Philippe's answer is correct.
But here's some information specific to Circumflex:
In the Circumflex RequestRouter, the following can be used to implement the required method:
def requireLogin (f: => RouteResponse ): RouteResponse = {
if(loggedIn) {
return f
}
else {
return sendRedirect("/login")
}
}
The reason behind this was getting clear with the hint from Jean-Philippe's answer, and once I remembered that the following call isn't an assignment of a block to some internal data, but is mapped to another method call instead.
So, the call
get("/") = {...}
is actually mapped to this:
get.update("/", {...})
The block is passed in as a By-Name parameter, so the return value of requireLogin must be the same - which, for Circumflex, is RouteResponse, and not a function.
You also can use j2ee container authentication with <login-config> and <security-constraint> stuff inside web.xml

What does () => mean in C#?

I've been reading through the source code for Moq and I came across the following unit test:
Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtLeast(0));
And for the life of me, I can't remember what () => actually does. I'm think it has something to do with anonymous methods or lambdas. And I'm sure I know what it does, I just can't remember at the moment....
And to make matters worse....google isn't being much help and neither is stackoverflow
Can someone give me a quick answer to a pretty noobish question?
Search StackOverflow for "lambda".
Specifically:
() => Console.WriteLine("Hi!");
That means "a method that takes no arguments and returns void, and when you call it, it writes the message to the console."
You can store it in an Action variable:
Action a = () => Console.WriteLine("Hi!");
And then you can call it:
a();
()=> is a nullary lambda expression. it represents an anonymous function that's passed to assert.Throws, and is called somewhere inside of that function.
void DoThisTwice(Action a) {
a();
a();
}
Action printHello = () => Console.Write("Hello ");
DoThisTwice(printHello);
// prints "Hello Hello "
It's a lambda expression. The most common syntax is using a parameter, so there are no parentheses needed around it:
n => Times.AtLeast(n)
If the number of parameters is something other than one, parentheses are needed:
(n, m) => Times.AtLeast(n + m)
When there are zero parameters, you get the somewhat awkward syntax with the parentheses around the empty parameter list:
() => Times.AtLeast(0)
() => Times.AtLeast(0)
() indicates that the lambda function has no parameters or return value.
=> indicates that a block of code is to follow.
Times.AtLeast(0) calls the Times class's static method AtLeast with a parameter of 0.
That's the definition of a lambda (anonymous) function. Essentially, it's a way to define a function inline, since Assert.Throws takes a function as an argument and attempts to run it (and then verify that it throws a certain exception).
Essentially, the snippet you have there is a unit test that makes sure Times.AtLeast(0) throws a ArgumentOutOfRangeException. The lambda function is necessary (instead of just trying to call the Times.AtLeast function directly from Assert.Throws) in order to pass the proper argument for the test - in this case 0.
MSDN KB article on the topic here: http://msdn.microsoft.com/en-us/library/bb882516.aspx
I don't program in C#, but Googling "C# Lambda" provided this link that answers your question!!!