Hi Players,
I read in a post here about Knockout, which has a cool concept to
simplify JavaScript UIs. So I tried to integrate it in my current Play
project and want to share some experiences and hope to get some
feedback I can learn from as I am a new player.
I want to offer in my view a select box of categories that can be
assigned to my object, I copied this line from the Knockout doc in my
html form and changed it a little.
Cat: <select data-bind="options: mainCategories, optionsText:
'name', value: chosenCategory"></select>
To have a binding for the two variables I used this:
<script type="text/javascript">
var viewModel = {
mainCategories: ko.observableArray($
{controllers.MainCategories.categoriesAsJson().raw()}),
chosenCategory: ko.observable($
{object.mainCategory?.toJson().raw()})
};
ko.applyBindings(viewModel); // Makes Knockout get to work
</script>
In the controller I added the following method to return my
categeories as JSON. I guess I cannot use templates here without
calling a render method. First I was struggling with an error because
of a circular reference to a SubCategory but this post [1] helped to
fix them using @Expose annotations.
public static String categoriesAsJson() {
List<MainCategory> mainCategories = MainCategory.findAll();
GsonBuilder gson = new
GsonBuilder().excludeFieldsWithoutExposeAnnotation(); // TODO: inject
return gson.create().toJson(mainCategories);
}
I got it to work half. My select box gets properly populated but the
element selection does not seem to work. Might be because my
chosenCategory JSON below is a little heavy weight because of the sub-
categories but the same rendering works for the select population.
chosenCategory: ko.observable({"name":"cursos /
enseñanza","children":[{"name":"idiomas","adCount":0},
{"name":"música / teatro / danza","adCount":0},{"name":"arte y
manualidades","adCount":0},
{"name":"informática / computación","adCount":0},
{"name":"conducción / manejo","adCount":0},
{"name":"universitaria","adCount":0},{"name":"cursos y
seminarios","adCount":0},
{"name":"deportes","adCount":0}],"adCount":0})
I also have not solved so far how to add an object to mainCategories
for non-selections like "None", "-" or "Please select a value".
Cheers,
Stefan
[1]
http://groups.google.com/group/play-framework/browse_thread/thread/faf73b1bf6f53d1d/a429a4487215654e?lnk=gst&q=json+circular#a429a4487215654e
--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To post to this group, send email to play-fr...@googlegroups.com.
To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.
I tried the value binding for single select:
http://knockoutjs.com/documentation/value-binding.html