Created
December 12, 2012 23:48
-
-
Save eltimn/4272796 to your computer and use it in GitHub Desktop.
This is an example of using knockout.js with Lift to create a form. It allows you to utilize all of knockout's form capabilities combined with Lift's built-in ajax callbacks. AnonFunc is used to create a JavaScript function that is passed to the view model and called when the form is submitted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(window) { | |
window.app = { | |
KoForm: function(saveFunc) { | |
var self = this; | |
self.name = ko.observable(""); | |
self.formJson = function() { | |
return {"name": self.name()}; | |
}; | |
self.save = function() { | |
console.log("save called. name: "+self.name()); | |
// call the save function passed in | |
saveFunc(); | |
}; | |
self.afterSave = function(name) { | |
console.log("afterSave called. name: "+name); | |
}; | |
} | |
}; | |
})(this); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<div id="ko-form" data-lift="KoForm.form"> | |
<form data-bind="submit: save"> | |
<input data-bind="value: name" /> | |
<button type="submit">Submit</button> | |
</form> | |
<script id="onload"></script> | |
</div> | |
<script src="app.js"></script> <!-- plus knockout --> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package code.snippet | |
import net.liftweb._ | |
import http.js._ | |
import http.js.JE._ | |
import http.js.JsCmds._ | |
import http.json._ | |
import util.Helpers._ | |
object KoForm { | |
def form = { | |
def save(jv: JValue): JsCmd = { | |
logger.debug("json: "+pretty(render(jv))) | |
val name = tryo((jv \ "name").extract[String]) openOr "" | |
Call("window.koForm.afterSave", name) | |
} | |
val saveFunc: JsExp = AnonFunc(SHtml.jsonCall(Call("window.koForm.formJson"), save _)) | |
val onLoad = | |
SetExp( | |
JsVar("window.koForm"), | |
CallNew("app.KoForm", saveFunc) | |
) & | |
Call("ko.applyBindings", JsVar("window.koForm"), Call("document.getElementById", "ko-form")) | |
"#id_onload" #> Script(OnLoad(onLoad)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment