Passing javascript event as parameter to Ajax in Lift?

129 views Asked by At

I am trying to implement DirtyForms-style validation library using Lift. What I'd like to do is send the event parameter from a click action to some server-side validation logic. I've found many answers to the problem of passing function arguments to Ajax, but none using Lift.

Here is what I have...

The DirtyField class is a class that keeps track of fields that have been 'dirtied'. Its method isDirty(): Boolean evaluates whether the field value has changed since the page was initialized (this works great).

class DirtyForm(fields: Seq[DirtyField[_]])
{
    val popupId = "popup"
    private def fieldsDirty(): JsCmd = fields.exists(_.isDirty) match {
        case true => Run("""function(e) { e.preventDefault(); $('#""" + popupId + """').dialog(); }""") //prevent them from clicking link if they need to save their data
        case false => Noop
    }
    def seq(): NodeSeq = {
        Script(Run("""
            $(document).ready(function() {
                $(document).on('click', 'a[href]', """ + SHtml.ajaxInvoke(() => fieldsDirty()).toJsCmd + """);
            });""".stripMargin)) ++ ConfirmationDiv(popupId) /*div with 'popup' as id*/
    }
}

Calling code:

def render = {
    //...
    val myDirtyForm = new DirtyForm(/*some fields to watch here*/)
    "* *+" #> myDirtyForm.seq()
}

Generated javascript:

<script>
// <![CDATA[
$(document).ready(function() {
    $(document).on('click', 'a[href]', liftAjax.lift_ajaxHandler("F1336229574104X2J5CL=true", null, null, null));
});
// ]]>
</script>

When this ajax call is invoked on a link click with a dirtied field, I get the following error in the console: The server call succeeded, but the returned Javascript contains an error: SyntaxError: Unexpected token (, which I expect to be because I am trying to use function() where it is not applicable.

TL;DR: My problem revolves around two things:

  1. I want to evaluate whether or not the form is dirty via ajax
  2. If it is dirty, I want to call preventDefault()

Disclaimer: this is my first post, so any suggestions on how to improve the question would be appreciated!

0

There are 0 answers